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

相关推荐
前端技术官4 分钟前
前端真的比后端简单吗?
javascript·webview·dom·前端工程化·浏览器兼容性
vx-程序开发11 分钟前
【java项目分享】springboot农产品销售平台14952
java·javascript·spring boot·python·eclipse·django·php
布兰妮甜19 分钟前
Vue 路由进阶:路由守卫权限控制、动态路由、懒加载、路由缓存
vue.js·懒加载·动态路由·路由守卫权限控制·路由缓存
Cobyte32 分钟前
Vite & Rollup 插件开发实践
前端·javascript·vue.js
朝阳3934 分钟前
react19【系列实用教程】实用组件封装
开发语言·前端·javascript
古韵43 分钟前
小程序上传进度条,还要自己监听 onProgressUpdate 吗?
前端·javascript·uni-app
古韵44 分钟前
axios 已经跑得好好的,还要不要上 alova?
前端·javascript·axios
噗噗121 小时前
企业微信侧边栏应用与前端 JS-SDK 的深度整合指南
前端·javascript·企业微信
朝阳391 小时前
react19【实战】配置化路由登录鉴权完整方案
前端·javascript·react.js
ShuiShenHuoLe1 小时前
vue如何实现国际化,它来了!
前端·javascript·vue.js