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

相关推荐
Dignity_呱几秒前
vue3对组件通信做了哪些升级?
前端·vue.js·面试
就是我3 分钟前
开发“业务组件库”,该从哪里入手?
前端·javascript·面试
Mintopia6 分钟前
在数字画布上雕刻曲线:NURBS 的奇幻冒险之旅
前端·javascript·计算机图形学
Mintopia14 分钟前
Three.js 力导向图:让数据跳起优雅的华尔兹
前端·javascript·three.js
晓得迷路了36 分钟前
栗子前端技术周刊第 84 期 - Vite v7.0 beta、Vitest 3.2、Astro 5.9...
前端·javascript·vite
独立开阀者_FwtCoder40 分钟前
最全301/302重定向指南:从SEO到实战,一篇就够了
前端·javascript·vue.js
Moment1 小时前
给大家推荐一个超好用的 Marsview 低代码平台 🤩🤩🤩
前端·javascript·github
明似水1 小时前
用 Melos 解决 Flutter Monorepo 的依赖冲突:一个真实案例
前端·javascript·flutter
独立开阀者_FwtCoder2 小时前
stagewise:让AI与代码编辑器无缝连接
前端·javascript·github
江城开朗的豌豆2 小时前
JavaScript篇:对象派 vs 过程派:编程江湖的两种武功心法
前端·javascript·面试