Top
Fork me on Gitee

Vue -- vant tabbar 点击切换高亮

在 vue-cli 移动项目中,使用 vant 底部切换,例如:/mine 和 /mine/collect 都需要"我的"高亮,点击"我的",回到 /mine 页面。使用vant文档中的 tabbar change 方法,点击"我的"不能触发 change 事件,所以可以点击每个 item 实现。刷新也要保留指定页面高亮。

页面数据可以循环显示,为了展示自定义图标,这里没有做data数据。

<van-tabbar v-model="active" active-color="#ee0a24" inactive-color="#000" :placeholder="true">
 <van-tabbar-item icon="home-o" @click="onClick('/')">首页</van-tabbar-item>
  <van-tabbar-item @click="onClick('/market')">
    <span>自定义</span>
    <template #icon="props">
      <img :src="props.active ? icon.active : icon.inactive" />
    </template>
  </van-tabbar-item>
  <van-tabbar-item icon="award-o" @click="onClick('/artist')">标签</van-tabbar-item>
  <van-tabbar-item icon="diamond-o" @click="onClick('/hotspot')">标签</van-tabbar-item>
  <van-tabbar-item icon="contact" @click="onClick('/mine')">我的</van-tabbar-item>
</van-tabbar>       
export default {
  data () {
    return {
      active: 0,
      icon: {
        active: 'https://img01.yzcdn.cn/vant/user-active.png',
        inactive: 'https://img01.yzcdn.cn/vant/user-inactive.png',
      }
    }
  },
  mounted () {
    this.handleActive()
  },
  watch: {
    $route () {
      this.handleActive()
    }
  },
  methods: {
    handleActive () {
      let path = this.$route.path
      if (path.indexOf('/market') !== -1) {
        this.active = 1
      } else if (path.indexOf('/artist') !== -1) {
        this.active = 2
      } else if (path.indexOf('/hotspot') !== -1) {
        this.active = 3
      } else if (path.indexOf('/mine') !== -1) {
        this.active = 4
      } else if (/\/(\?.)*$/.test(path)) {
        this.active = 0
      } else {
        this.active = -1
      }
    },
    onClick (path) {
      if (this.$route.path !== path) {
        this.$router.push({ path })
      }
    }
  }
}
posted @ 2022-05-06 17:54  lisashare  阅读(877)  评论(0编辑  收藏  举报