vue3+ts实现Tab滚动居中

html 复制代码
<template>
  <div class="tab-container">
    <div class="tab-list" ref="tabList">
      <div
        v-for="(tab, index) in tabs"
        :key="index"
        :class="['tab', { active: activeTab === index }]"
        @click="changeTab(index)"
      >
        {{ tab }}
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { ref, onMounted } from 'vue';

export default {
  name: 'TabContainer',
  data() {
    return {
      tabs: ['Tab 1', 'Tab 2', 'Tab 3', 'Tab 4', 'Tab 5'],
      activeTab: 0,
    };
  },
  mounted() {
    onMounted(() => {
      this.centerActiveTab();
    });
  },
  methods: {
    changeTab(index: number) {
      this.activeTab = index;
      this.centerActiveTab();
    },
    centerActiveTab() {
      const tabList = this.$refs.tabList as HTMLElement;
      const activeTab = tabList.querySelector('.active') as HTMLElement;

      if (activeTab) {
        const containerWidth = tabList.offsetWidth;
        const activeTabWidth = activeTab.offsetWidth;
        const activeTabLeft = activeTab.offsetLeft;

        const scrollLeft = activeTabLeft - (containerWidth - activeTabWidth) / 2;
        tabList.scrollTo({
          left: scrollLeft,
          behavior: 'smooth',
        });
      }
    },
  },
};
</script>

<style scoped>
.tab-container {
  width: 100%;
  overflow-x: auto;
}

.tab-list {
  display: flex;
}

.tab {
  padding: 10px;
  cursor: pointer;
}

.active {
  font-weight: bold;
}
</style>

TabContainer组件中使用了ref来获取到tabList元素的引用,然后在mounted钩子函数中调用centerActiveTab方法来初始化时居中显示当前激活的Tab。

changeTab方法中,切换Tab时,会更新activeTab的值,并调用centerActiveTab方法来将新的激活Tab居中显示。

centerActiveTab方法中,首先获取到tabList和当前激活的Tab元素的引用,然后计算出滚动的位置,使激活的Tab居中显示。通过调用scrollTo方法来实现滚动效果。

最后,在样式中设置了容器的宽度为100%,并设置了overflow-x: auto来实现水平滚动的效果。每个Tab元素设置了一些基本的样式,激活的Tab元素设置了加粗的字体。

相关推荐
daols8819 分钟前
vxe-table 配置 ajax 加载列表数据,配置分页和查询搜索表单
vue.js·ajax·table·vxe-table
没头脑的男大27 分钟前
Unet实现脑肿瘤分割检测
开发语言·javascript·ecmascript
~无忧花开~44 分钟前
Vue.config.js配置全攻略
开发语言·前端·javascript·vue.js
w***Q3501 小时前
前端跨平台开发工具,Tauri与Electron
前端·javascript·electron
幸会同学2 小时前
在Cesium中实现飘动的红旗
javascript·three.js·cesium
默默乄行走2 小时前
wangEditor5在vue中自定义菜单栏--格式刷,上传图片,视频功能
vue.js
G***66912 小时前
前端框架选型:React vs Vue深度对比
vue.js·react.js·前端框架
flypwn2 小时前
justCTF 2025JSpositive_player知识
开发语言·javascript·原型模式
孤狼warrior3 小时前
公司信息建设库数据 使用调用堆栈的JS逆向爬虫
javascript·爬虫
泯泷4 小时前
Tiptap 深度教程(四):终极定制 - 从零创建你的专属扩展
前端·javascript·架构