vue 監聽路由變化
阿新 • • 發佈:2018-04-06
scrip rip 不同的 bsp ted 監聽 brush 通過 deep
方法一:通過 watch
// 監聽,當路由發生變化的時候執行 watch:{ $route(to,from){ console.log(to.path); } },
或
// 監聽,當路由發生變化的時候執行 watch: { $route: { handler: function(val, oldVal){ console.log(val); }, // 深度觀察監聽 deep: true } },
或
// 監聽,當路由發生變化的時候執行 watch: { ‘$route‘:‘getPath‘ }, methods: { getPath(){ console.log(this.$route.path); } }
方法二::key是用來阻止“復用”的。
Vue 為你提供了一種方式來聲明“這兩個元素是完全獨立的——不要復用它們”。只需添加一個具有唯一值的 key
屬性即可(Vue文檔原話)
<router-view :key="key"></router-view> computed: { key() { return this.$route.name !== undefined? this.$route.name +new Date(): this.$route +new Date() } }
使用computed屬性和Date()可以保證每一次的key都是不同的,這樣就可以如願刷新數據了。
.
vue 監聽路由變化