vue中對於每一個組件(vue文件),都提供了在路由進入前的攔截或者說是提前操作,比如在需求中遇到的問題——需要在路由進入前判斷是否是移動端訪問,如果是移動端訪問,則進行路由跳轉。以前的前端把這項攔截寫在了router文件下的路由表中,導致了路由權限配置到系統數據庫不是很好處理。所以把這個判斷條件移動到組件內。正好這種功能vue提供了beforeRouteEnter等函數進行調用。
const Foo = {
template: `...`,
beforeRouteEnter (to, from, next) {
// 在渲染該組件的對應路由被 confirm 前調用
// 不!能!獲取組件實例 `this`
// 因爲當守衛執行前,組件實例還沒被創建
},
beforeRouteUpdate (to, from, next) {
// 在當前路由改變,但是該組件被複用時調用
// 舉例來說,對於一個帶有動態參數的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉的時候,
// 由於會渲染同樣的 Foo 組件,因此組件實例會被複用。而這個鉤子就會在這個情況下被調用。
// 可以訪問組件實例 `this`
},
beforeRouteLeave (to, from, next) {
// 導航離開該組件的對應路由時調用
// 可以訪問組件實例 `this`
}
}
- to:Route:即將進入的目標路由對象。
- from:Route:當前導航正要離開的路由
- next:Function:一定要調用該方法來resolve這個鉤子。
下面是使用beforeRouteEnter的例子:
http://jsfiddle.net/HunterYoung/L7hscd8h/23446/
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
<p>
<router-link to="/one">one</router-link><br>
<router-link to="/one_two">one_two</router-link><br>
<router-link to="/two_one">two_one</router-link><br>
<router-link to="/two_two">two_two</router-link><br>
</p>
<transition name="fade" mode="out-in">
<router-view></router-view>
</transition>
</div>
Vue.mixin({
beforeRouteEnter (to, from, next) {
next(vm => {
console.log('vm.title:', vm.title)
})
},
mounted () {
console.log(this.$vnode.tag + ': mounted')
}
})
const FirstComponent = Vue.extend({
template: `<div>First component</div>`,
props: {
title: String
}
})
const SecondComponent = Vue.extend({
template: `<div>Second component</div>`,
props: {
title: String
}
})
const router = new VueRouter({
routes: [
{ path: '/one', component: FirstComponent, props: { title: 'one' } },
{ path: '/one_two', component: FirstComponent, props: { title: 'one_two' } },
{ path: '/two_one', component: SecondComponent, props: { title: 'two_one' } },
{ path: '/two_two', component: SecondComponent, props: { title: 'two_two' } }
]
})
const app = new Vue({ router }).$mount('#app')