用到vue-router的導航鉤子的時候,發(fā)現(xiàn)有三類:
1 、全局導航鉤子
beforeEach
beforeResolve
afterEach
2 、某個路由獨享的導航鉤子
beforeEnter
3 、路由組件上的導航鉤子
beforeRouteEnter
beforeRouteUpdate (2.2 新增)
beforeRouteLeave
下面來舉例說明一下區(qū)別
全局導航鉤子
const router = new VueRouter({
mode: 'history', // 路由使用history模式
routes,
linkActiveClass: 'active', // 設置當前路由的className
});
// 全局導航鉤子 直接掛載在router實例上的
router.beforeEach((to, from, next) => {
document.title = to.meta.title || 'demo'
if (!to.query.url && from.query.url) {
to.query.url = from.query.url
}
next()
})
router.afterEach(route => {
})
某個路由獨享的導航鉤子
{
path: '/',
component: App,
children: [
{
path: 'apply',
name: 'apply',
component: Apply,
children: [
{
path: 'launch',
name: 'apply-launch-list',
component: applyList,
// 直接在router的路由配置中使用
beforeEnter (to, from, next) {
// 如果isBack為true時,證明是用戶點擊了回退,執(zhí)行slide-right動畫
let isBack = this.$store.state.transferBack;
if (isBack) {
this.transitionName = 'slide-right';
} else {
this.transitionName = 'slide-left';
}
// 做完回退動畫后,要設置成前進動畫,否則下次打開頁面動畫將還是回退
this.$router.isBack = false;
next()
}
},
{
path: 'draft',
name: 'apply-draft-list',
component: draftList
}
]
}
]
}
路由組件上的導航鉤子
// 定義一個vue模板,這個模板被router的配置文件的component使用
const Qux = {
data () {
return {
msg: null
}
},
template: `<div>{{ msg }}</div>`,
// 路由組件上的導航鉤子beforeRouteEnter
beforeRouteEnter (to, from, next) {
setTimeout(() => {
next(vm => {
vm.msg = 'Qux'
})
}, 300)
}
}
const router = new VueRouter({
mode: 'history',
base: __dirname,
routes: [
{ path: '/', component: Home },
// 某個路由獨享的導航鉤子beforeEnter
{ path: '/foo', component: Foo, beforeEnter: guardRoute },
{ path: '/bar', component: Bar, meta: { needGuard: true }},
// 在這里使用Qux
{ path: '/qux', component: Qux },
{ path: '/qux-async', component: resolve => {
setTimeout(() => {
resolve(Qux)
}, 0)
} },
{ path: '/quux/:id', component: Quux }
]
})