mint ui的tabBar监听路由变化实现tabBar切换

说明

  • 最近学习vue,使用了mint uitabBar,感觉好难受,结合 tab-container使用更难受,因为它不是根据路由来切换页面的。mui与它基本相反,因此它能根据搜索栏的路由变化,相应的tabBar高亮显示,而mint ui就不能,要加点代码实现了。

  • mint ui tabBar标签栏
    //页面 和 数据
    <template>
        <div id="main">
            <mt-tabbar v-model="selected">
                <mt-tab-item :id="home">
                    首页
                </mt-tab-item>
                <mt-tab-item :id="car">
                    购物车
                </mt-tab-item>
                <mt-tab-item :id="person">
                    我的
                </mt-tab-item>
            </mt-tabbar>
        </div>
    </template>

    <script>
        export default {
            data(){
                return {
                    //页面刷新取数据
                    selected: sessionStorage.getItem('selected')? JSON.parse(sessionStorage.getItem('selected')):'首页',
                    home: '首页',
                    car: '购物车',
                    person: '我的',      
                }
            }
        }
    </script>
  • 监听路由的变化
    • 监听路由的变化,那就要使用到侦听器 watch 了。一旦selected变化,就保存到 sessionStorage,当页面刷新的时候,在初始化数据取出即可。
     watch: {
          selected(val, oldVal){
              //一旦标签栏变化,把selected的值存到sessionStorage,保存当前值
              sessionStorage.setItem('selected', JSON.stringify(val))
              if(val === this.home){
                  //路由跳转 到首页
                  this.$router.replace('/home')          
              }else if(val === this.car){
                  //路由跳转 到购物车
                  this.$router.replace('/car')            
              }else if(val === this.person){
                  //路由跳转 到个人中心
                  this.$router.replace('/person')           
              }
          }

猜你喜欢

转载自www.cnblogs.com/HJ412/p/10771645.html