Vue 中使用watch监听$route 无效问题

2022-08-01,,,,

Vue 中使用watch监听$route失效问题!

路由:
{
      name: 'secondUser ',
      component: secondUser,
      path: '/secondUser',
}
-------------------------------------------------------------------------------------------------------------------
页面中监听
 watch:{
        '$route'(to,from) {   
            console.log(to,from);
        }
    },

结果我们发现在路由跳转后,我们的console并没有输出东西,加了断点发现也并没有执行到里面,原来,我们用watch监听路由变化,我们的路由一定要有子路由,监听变化也紧局限在父子路由中,也就是我们这个路由一定要有子路由,在子路由跳转过程中会调用watch,能成功监听!

我们为secondUser路由增加了两个子路由!
我们发现在进行父子路由跳转过程中,我们的watch可以坚挺到路由变化了!
{
      name: 'secondUser ',
      component: secondUser,
      path: '/secondUser',
      children: [
        {
        path: 'user',
        name: 'user',
        component: user,
        },
        {
        path: 'userName',
        name: 'userName',
        component: userName,
        },
      ]
    },

因此我们可以使用vue组件独享守卫钩子函数参数详解(beforeRouteEnter、beforeRouteUpdate、beforeRouteLeave)

<template>
  <div class="test_box">
    <p @click="goBack">按钮</p>
  </div>
</template>
<script>
export default {
  data() {
    return {

    }
  },
  methods: {
    goBack() {
      this.$router.push({ name: 'HelloWorld' })
    }
  },
  beforeRouteEnter(to, from, next) {
    console.log(this, 'beforeRouteEnter'); // undefined
    console.log(to, '组件独享守卫beforeRouteEnter第一个参数');
    console.log(from, '组件独享守卫beforeRouteEnter第二个参数');
    console.log(next, '组件独享守卫beforeRouteEnter第三个参数');
    next(vm => {
      //因为当钩子执行前,组件实例还没被创建
      // vm 就是当前组件的实例相当于上面的 this,所以在 next 方法里你就可以把 vm 当 this 来用了。
      console.log(vm);//当前组件的实例
    });
  },
  beforeRouteUpdate(to, from, next) {
    //在当前路由改变,但是该组件被复用时调用
    //对于一个带有动态参数的路径 /good/:id,在 /good/1 和 /good/2 之间跳转的时候,
    // 由于会渲染同样的good组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
    console.log(this, 'beforeRouteUpdate'); //当前组件实例
    console.log(to, '组件独享守卫beforeRouteUpdate第一个参数');
    console.log(from, '组件独享守beforeRouteUpdate卫第二个参数');
    console.log(next, '组件独享守beforeRouteUpdate卫第三个参数');
    next();
  },
  beforeRouteLeave(to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
    console.log(this, 'beforeRouteLeave'); //当前组件实例
    console.log(to, '组件独享守卫beforeRouteLeave第一个参数');
    console.log(from, '组件独享守卫beforeRouteLeave第二个参数');
    console.log(next, '组件独享守卫beforeRouteLeave第三个参数');
    next();
  }
}

</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>


</style>

本文地址:https://blog.csdn.net/Ares0412/article/details/107486641

《Vue 中使用watch监听$route 无效问题.doc》

下载本文的Word格式文档,以方便收藏与打印。