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

该文章展示了一个Vue组件,用于创建可接受任意数量选项的顶部菜单导航。组件包含切换动画,底部有高亮图片,并能根据传入的索引值自动设置高亮。点击菜单项时,会触发changeTab事件,向父组件传递当前选中的内容。
摘要由CSDN通过智能技术生成

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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值