通过click事件来修改currentIndex的值,这样一来class绑定的对应的 样式就会自己判断样式

组件间激活的方法:

父组件传递参数:

代码:

<tab-bar-item path="/home" activeColor="pink">
  <img slot="item-icon" src="~assets/img/tabbar/home.svg" alt="">
  <img slot="item-icon-active" src="~assets/img/tabbar/home_active.svg" alt="">
  <div slot="item-text">首页</div>
</tab-bar-item>
<tab-bar-item path="/category" activeColor="pink">
  <img slot="item-icon" src="../../assets/img/tabbar/category.svg" alt="">
  <img slot="item-icon-active" src="../../assets/img/tabbar/category_active.svg" alt="">
  <div slot="item-text">分类</div>

子组件

<template>
  <!--所有的item都展示同一个图片, 同一个文字-->
  <div class="tab-bar-item" @click="itemClick">
    <div v-if="!isActive"><slot name="item-icon"></slot></div>
    <div v-else><slot name="item-icon-active"></slot></div>
    <div :style="activeStyle"><slot name="item-text"></slot></div>
  </div>
</template>
<script>
  export default {
    name: "TabBarItem",
    props: {
      path: String,
      activeColor: {
        type: String,
        default: 'red'
      }
    },
    computed: {
      isActive() {
        return this.$route.path.indexOf(this.path) !== -1
      },
      activeStyle() {
        return this.isActive ? {color: this.activeColor} : {}
      }
    },
    methods: {
      itemClick() {
        // 用这个方法进行路由间的切换,前提是已经注册过了路由
        this.$router.replace(this.path)
      }
    }
  }
</script>

<style scoped>
  .tab-bar-item {
    flex: 1;
    text-align: center;
    height: 49px;
    font-size: 14px;
  }

  .tab-bar-item img {
    width: 24px;
    height: 24px;
    margin-top: 3px;
    vertical-align: middle;
    margin-bottom: 2px;
  }
</style>

效果

 

 

Logo

前往低代码交流专区

更多推荐