用到vue-router的导航钩子的时候,发现有三类:
1 、全局导航钩子
beforeEach
beforeResolve
afterEach
2 、某个路由独享的导航钩子
beforeEnter
3 、路由组件上的导航钩子
beforeRouteEnter
beforeRouteUpdate (2.2 新增)
beforeRouteLeave
下面来举例说明一下区别
全局导航钩子
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时,证明是用户点击了回退,执行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 }
]
})
网友评论