uni-app 自定义 tab 选项卡 2 - 潇洒哥gg app下划线偏移

uni-app 自定义 tab 选项卡 2 - 潇洒哥gg app下划线偏移

[v-tabs
ref=“tabs”
v-model=“current”
fixed
tabs=“tabs” scroll=“false” @change=“changeTab”]



this.tabs = ["基础信息", "组态图", "监控", "设备"];
this.$nextTick(() => {
this.$refs.tabs.update();
});

图片


更多关于uni-app 自定义 tab 选项卡 2 - 潇洒哥gg app下划线偏移的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于uni-app 自定义 tab 选项卡 2 - 潇洒哥gg app下划线偏移的实战教程也可以访问 https://www.itying.com/category-93-b0.html


在uni-app中自定义tab选项卡时,如果遇到下划线偏移的问题,通常是因为样式或者逻辑处理不当导致的。以下是一个示例代码,展示如何自定义tab选项卡并正确处理下划线位置。

首先,我们需要在页面的<template>部分定义tab选项卡的布局:

<template>
  <view class="container">
    <view class="tabs">
      <view 
        v-for="(tab, index) in tabs" 
        :key="index" 
        class="tab-item" 
        @click="switchTab(index)"
        :class="{ active: currentIndex === index }"
      >
        {{ tab.name }}
      </view>
      <view class="underline" :style="{ left: underlinePosition + 'px' }"></view>
    </view>
    <view class="content">
      <!-- 这里是各个tab对应的内容 -->
      <view v-if="currentIndex === 0">Tab 1 内容</view>
      <view v-if="currentIndex === 1">Tab 2 内容</view>
      <!-- 更多tab内容... -->
    </view>
  </view>
</template>

接下来,在<script>部分定义数据和逻辑:

<script>
export default {
  data() {
    return {
      tabs: [
        { name: 'Tab 1' },
        { name: 'Tab 2' },
        // 更多tab...
      ],
      currentIndex: 0,
      underlinePosition: 0,
      tabWidth: 0,
    };
  },
  methods: {
    switchTab(index) {
      this.currentIndex = index;
      this.underlinePosition = index * this.tabWidth;
    },
  },
  mounted() {
    this.$nextTick(() => {
      const tabItems = this.$el.querySelectorAll('.tab-item');
      this.tabWidth = tabItems[0].offsetWidth;
      // 初始化时设置下划线位置
      this.underlinePosition = this.currentIndex * this.tabWidth;
    });
  },
};
</script>

最后,在<style>部分定义样式:

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.tabs {
  display: flex;
  justify-content: space-around;
  position: relative;
}
.tab-item {
  padding: 10px;
  flex: 1;
  text-align: center;
}
.tab-item.active {
  color: red; /* 激活状态的样式 */
}
.underline {
  position: absolute;
  bottom: 0;
  height: 4px;
  background-color: red;
  transition: left 0.3s;
}
.content {
  flex: 1;
  padding: 20px;
}
</style>

以上代码示例展示了如何自定义tab选项卡,并通过计算每个tab的宽度来设置下划线的位置。注意,$nextTick确保在DOM更新后获取正确的tab宽度。如果下划线仍然偏移,请检查是否有其他CSS样式影响了tab的宽度或位置。

回到顶部