tab 点击按钮平滑滚动中心点

80 阅读1分钟

1. 点击tab

点击tab, 当前点击的平滑滚动到中心点位置

image.png

image.png

2. 实现代码

<template>
    <div class="container">
      <ul class="tabs" ref="tabListRef">
        <li v-for="(v, i) in tabArray" :key="i" @click="tabsclick(v, i)">
          <span :class="seledIndex == i ? 'lised' : ''">{{ v.name }} </span>
        </li>
      </ul>
    </div>
</template>  

<script>
    export default {
      name: 'demo',
      data() {
        return {
            tabArray:[{...},{...}],
            seledIndex: 0,
            currentScrollIndex: 0,
        }
      },
    watch: {
        currentScrollIndex(newVal) {
          const tabList = this.$refs.tabListRef;
          const tab = tabList.children[newVal];
          const tabRect = tab.getBoundingClientRect();
          const scrollLeft =
            tab.offsetLeft + tabRect.width / 2 - window.innerWidth / 2;

          // tabList.scrollLeft = scrollLeft;
          tabList.scrollTo({
            left: scrollLeft,
            behavior: 'smooth' 
          });
        },
      },
      methods: {
          tabsclick(value, index) {
              this.seledIndex = index,
              currentScrollIndex = index,
          }
      }
    }
</script>