Tab 如何滚动居中

<template>
  <div class="tab-list" ref="tabListRef">
    <div
      v-for="(item, index) in tabList"
      :key="item"
      :class="index === currentIndex ? 'active-item' : 'tab-item'"
      @click="onTabClick(index)"
    >
      {{ item }}
    </div>
  </div>
</template>

<script>
export default {
  name: "TabList",
  props: {
    tabList: {
      type: Array,
    },
  },
  data() {
    return {
      currentIndex: 0,
    };
  },
  methods: {
    onTabClick(index) {
      this.currentIndex = index;
    },
  },
  watch: {
    currentIndex(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;
    },
  },
};
</script>

<style lang="less" scoped>
.tab-list {
  display: flex;
  width: 100%;
  flex-wrap: nowrap;
  overflow-x: scroll;
  .tab-item,
  .active-item {
    flex: 1;
    flex-shrink: 0;
    flex-basis: 200px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 200px;
    height: 40px;
    border-right: 1px solid #000;
    font-size: 16px;
    background-color: #8ce397;
  }
  .active-item {
    background-color: #f93c7d;
  }
}
</style>

你可能感兴趣的:(前端,javascript,css)