Vue之watch路由跳轉
阿新 • • 發佈:2019-01-26
可能應用的場景:比如我當前是個介紹新聞資訊的頁面,它的子路由是點選某條新聞跳轉到的詳情元件,實現思路倒很簡單:
主路由的新聞列表寫在一個div裡,並給該div一個v-if=”news”,當監測到路由處於新聞資訊的主路由就讓news等於true,即顯示。如果不在主路由(比如跳轉去子路由詳情頁面)則為false,如下:
router.js:
{
path: '/new',
name: 'new',
component: news,
children: [
{
path: '/new/newDetail',
name: 'newDetail' ,
component: newsDetail
}
]
}
新聞資訊主路由的元件template:
<template>
<div class="wrapper">
<div class="news" v-if="news">
這裡是新聞列表
</div>
<router-view></router-view> <-- 這個容器是顯示跳轉後的詳情元件 -->
</div>
</template>
監控路由的js如下:
export default {
created () {// 每次路由變化dom重新載入都會執行該方法
this.historyWatch();
},
watch: {
// 路由若是發生變化,會再次執行該方法
'$route': 'historyWatch';
},
methods: {
historyWatch () {
this.news = (this.$route.path === '/new' ? 1 : 0);
}
}
}