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元素设置了加粗的字体。

相关推荐
爱心发电丶6 分钟前
基于UniappX开发电销APP,实现CRM后台控制APP自动拨号
javascript
地狱恶犬萨煤耶8 分钟前
JavaScript-实现函数方法-改变this指向call apply bind
javascript
地狱恶犬萨煤耶11 分钟前
JavaScript-小游戏-单词消消乐
javascript
tyro曹仓舒38 分钟前
干了10年前端,才学会使用IntersectionObserver
前端·javascript
李剑一2 小时前
我用Trae生成了一个Echarts 3D柱状图的Demo
前端·vue.js·trae
mine_mine2 小时前
油猴脚本拦截fetch和xhr请求,实现修改服务端接口功能
javascript
一 乐2 小时前
宠物猫店管理|宠物店管理|基于Java+vue的宠物猫店管理管理系统(源码+数据库+文档)
java·前端·数据库·vue.js·后端·宠物管理
熊猫比分管理员2 小时前
【全栈源码解决方案】Vue+Java四端齐全,一周交付可运行项目!
java·前端·vue.js
o***74172 小时前
【Nginx 】Nginx 部署前端 vue 项目
前端·vue.js·nginx
一 乐2 小时前
考公|考务考试|基于SprinBoot+vue的考公在线考试系统(源码+数据库+文档)
前端·javascript·数据库·vue.js·spring boot·课程设计