vue导航组件,支持传入n项

vue的顶部菜单导航组件,可以传入n项,带切换动画的,底部是图片,也可以用代码写,接受传入自定义高亮索引

<template>
    <van-sticky>
        <div class="menu-bar">
            <span
                :class="item.value == activeValue ? 'active' : ''"
                v-for="(item, index) in tabData"
                :key="item.value"
                @click="changeTab(item, index)"
                >
                {
    
    {item.text}}
            </span>
            <img 
                class="menu-active"
                src="../assets/tab-active.png"
                :style="'width: 18px;transform: translateX(' + translateXdistence + 'px) translateX(-50%); transition-duration: 0.3s;'"
            >
        </div>
    </van-sticky>
</template>

<script>
export default {
  data() {
    return {
      translateXdistence: 0,
      activeValue: '',
      activeIndex: 1
    };
  },
  props: {
    // 菜单数组,严格接受数组内属性名text&value
    tabData: {
      type: Array,
      default: []
    },
    // 接受默认选项索引的改变,从1开始计算
    index: {
      type: Number,
      default: 1
    }
  },
  created() {
  },
  mounted() {
    this.computedX();
    this.activeValue = this.tabData[this.index - 1].value || '';
    this.activeIndex = this.index;
  },
  methods: {
    changeTab (item, index) {
      this.activeIndex = index + 1;
      this.activeValue = item.value;
      this.computedX();
      this.$emit('changeTab', item);// 传给父组件 当前切换后的内容
    },
    // 计算初始化的选中图标位置
    computedX () {
      let allwidth = window.innerWidth;
      let unitWidth = allwidth / this.tabData.length;
      this.translateXdistence = this.activeIndex * unitWidth - unitWidth / 2;
    }
  }
};
</script>

<style lang="less">
.menu-bar {
    color: #2D2F32;
    width: 100%;
    height: 88px;
    line-height: 88px;
    font-size: 28px;
    display: flex;
    justify-content: space-around;
    background: #fff;
    position: relative;
    border-bottom: 12px solid #F1F3F4;
    .menu-active {
        position: absolute;
        bottom: 0;
        left: 0;
    }
    .active {
        font-weight: 500;
    }
}
</style>

父组件调用

<MenuBar :tabData="tabData" @changeTab="changeTab"></MenuBar>

猜你喜欢

转载自blog.csdn.net/qq_38068508/article/details/129306608