vue2,根据当前路由路径,来决定某块标签的显示与否v-show

85 阅读1分钟

技术栈 使用了若依框架

目标

在除了aiChat页面以外的所有页面,展示该图标。因为点击该图标会跳转到aiChat页面。

image.png

最终方法

在图标页面内,通过computed计算

    <!-- ai标志 -->
    <div v-show="!isChatPage" class="aiChat" @click="goChat">
      <img src="@/assets/myIcons/chatIcon.png" alt="" />
    </div>

  computed: {
    isChatPage() {
      return this.$route.path === "/aiChat";
    },
  }

错误的踩坑记录

1.用 watch 监视当前路由

  watch: {
    $route(to, from) {
      // 当需要监视的数据属性发生变化时触发的回调函数
      if (to.path === "/aiChat") {
        this.isChatPage = true;
         console.log(this.isChatPage);
      } else {
        this.isChatPage = false;
        onsole.log(this.isChatPage);
      }
    },
  },
  
  //即使不用函数的写法依旧:输出正常,v-show不生效
   watch: {
    $route: {
      immediate: true, // 一旦监听到路由的变化立即执行
      handler(to) {
        this.isChatPage = to.path == "/aiChat";
        console.log('this.isChatPage',this.isChatPage);
      },
    },
  },

可以输出isChatPage变换后的值,但是图标不会变换显示、隐藏。不知道为啥。。。

2.用路由守卫 (虽然可以在vue页面使用路由守卫,但路由守卫应该放在router的js文件内统一管理,才符合规范。)

  beforeCreate() {
   console.log(this.$route.path);
   if (this.$route.path == "/aiChat") {
     console.log("进入了页面");
   } else {
     this.isChatPage = false;
   }
 },

同样的,可以输出isChatPage变换后的值,但是v-show不生效。不知道为啥。。。