在 vue js 上观察路由对象

Watch route object on vue js

如何在 vue js 上查看路由对象?.这是我的代码

watch: { 
     '$route.params.search': function(search) {
           console.log(search)
      }
}

没用。

我尝试使用 deep 仍然无法在 here

上使用

查看代码 sanbox,您可以在 main.js 上查看路由对象。

You should not watch for the route object inside any other components. Because components get destroyed when router link changes. You should do it in the main.js file, according to your directory structure

感谢@santanu 和@ittus

您尝试过 deep 选项吗?

watch: { 
     '$route.params.search': {
        handler: function(search) {
           console.log(search)
        },
        deep: true,
        immediate: true
      }
}

在我的代码中,我确实喜欢以下内容 -

watch:{
    '$route' (to, from){
        // Put your logic here...
    }
},

不要注意任何其他组件内的 $route 对象。因为当路由器 link 发生变化时,组件被销毁并正在安装新组件。所以组件的观察者被破坏了。 在注入 router 对象的根 Vue 实例中观察 $route 对象。像下面这样 --

const app = new Vue({
    router,
    watch:{
        '$route' (to, from){
           // Code
        }
    }
}).$mount('#element');

使用简单:

watch: {
    "$route.params.search"(value) {
      //Your code here
    }
  }

我在反应性方面遇到了问题,使用 router-link 动态更改路线。

问题是路线会改变,但我从 data() 返回的方法中获取的 siteData 不是:

我不得不这样看路线:

    watch: {
      '$route' (to, from) {
        if(to !== from ) {
          this.siteData = this.getSiteData();
        }
      }
    },

希望这可以帮助其他人解决这个问题