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

相关推荐
用户83134859306982 小时前
Cesium自定义可调节星空夜景+星星闪烁
vue.js·cesium
后台开发者Ethan2 小时前
setState组件更新
前端·javascript·react
蜡台3 小时前
uniapp vue2 转 vue3
前端·javascript·uni-app·vue3·vue2
WindfallSheng3 小时前
从Vibe Coding到Spec Coding:一套可落地的AI-SDD企业级研发实战工程
javascript·vue.js
Asize4 小时前
Agent 入门:从 LLM 与 Agent 的区别到 Function Calling
javascript·人工智能
我有满天星辰4 小时前
Vue 指令完全指南:从 Vue 2 到 Vue 3 的演进与实战
前端·javascript·vue.js
小白学过的代码4 小时前
# flv.js / mpegts.js 播不了国标摄像头(H.265 + G.711A)?纯前端 Jessibuca 无后端方案(附完整代码)
前端·javascript·h.265
我有满天星辰7 小时前
Vue 3 响应式双雄:ref 与 reactive 完全指南
前端·javascript·vue.js
随风一样自由15 小时前
【前端独角兽】刚进入前端领域的前端开发用jQuery还是Vue3?
前端·javascript·vue3·jquery
YHHLAI16 小时前
[特殊字符] 面试中的 Promise —— 从入门到精通
前端·javascript·面试