方法一:通過(guò) watch
// 監(jiān)聽(tīng),當(dāng)路由發(fā)生變化的時(shí)候執(zhí)行
watch:{
$route(to,from){
console.log(to.path);
}
},
或者
// 監(jiān)聽(tīng),當(dāng)路由發(fā)生變化的時(shí)候執(zhí)行
watch: {
$route: {
handler: function(val, oldVal){
console.log(val);
},
// 深度觀察監(jiān)聽(tīng)
deep: true
}
},
或者
// 監(jiān)聽(tīng),當(dāng)路由發(fā)生變化的時(shí)候執(zhí)行
watch: {
'$route':'getPath'
},
methods: {
getPath(){
console.log(this.$route.path);
}
}
方法二::key是用來(lái)阻止“復(fù)用”的搔预。
Vue 為你提供了一種方式來(lái)聲明“這兩個(gè)元素是完全獨(dú)立的——不要復(fù)用它們”钻心。只需添加一個(gè)具有唯一值的 key 屬性即可(Vue文檔原話)
使用computed屬性和Date()可以保證每一次的key都是不同的舵稠,這樣就可以如愿刷新數(shù)據(jù)了史飞。
<router-view :key="key"></router-view>
computed: {
key() {
return this.$route.name !== undefined? this.$route.name +new Date(): this.$route +new Date()
}
}
方法三:通過(guò) vue-router 的鉤子函數(shù) beforeRouteEnter beforeRouteUpdate beforeRouteLeave
<script>
export default {
name: 'app',
// 監(jiān)聽(tīng),當(dāng)路由發(fā)生變化的時(shí)候執(zhí)行
beforeRouteEnter (to, from, next) {
// 在渲染該組件的對(duì)應(yīng)路由被 confirm 前調(diào)用
// 不牵舱!能喧务!獲取組件實(shí)例 `this`
// 因?yàn)楫?dāng)鉤子執(zhí)行前赖歌,組件實(shí)例還沒(méi)被創(chuàng)建
},
beforeRouteUpdate (to, from, next) {
// 在當(dāng)前路由改變,但是該組件被復(fù)用時(shí)調(diào)用
// 舉例來(lái)說(shuō)功茴,對(duì)于一個(gè)帶有動(dòng)態(tài)參數(shù)的路徑 /foo/:id庐冯,在 /foo/1 和 /foo/2 之間跳轉(zhuǎn)的時(shí)候,
// 由于會(huì)渲染同樣的 Foo 組件坎穿,因此組件實(shí)例會(huì)被復(fù)用展父。而這個(gè)鉤子就會(huì)在這個(gè)情況下被調(diào)用返劲。
// 可以訪問(wèn)組件實(shí)例 `this`
},
beforeRouteLeave (to, from, next) {
// 導(dǎo)航離開(kāi)該組件的對(duì)應(yīng)路由時(shí)調(diào)用
// 可以訪問(wèn)組件實(shí)例 `this`
}
</script>
原文作者:匆匆那年_海,博客主頁(yè):http://www.reibang.com/u/910c0667c515
95后前端漢子栖茉,愛(ài)編程篮绿、優(yōu)秀、聰明吕漂、理性亲配、沉穩(wěn)、智慧的程序猿一枚痰娱。