vue开发之路由守卫
貌似除了
router.afterEach
每个守卫方法接收三个参数,router.afterEach
少了next:
-
to: Route: 即将要进入的目标 路由对象
-
from: Route: 当前导航正要离开的路由
-
next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数
//全局守卫
const router = new VueRouter({ ... })
//跳转之前
router.beforeEach((to, from, next) => {
console.log('在每次路由切换成功进入激活阶段时被调用')
})
//跳转之前,
# 全局后置钩子
router.beforeResolve((to, from, next) => {
console.log('router.beforeResolve 注册一个全局守卫。这和 router.beforeEach 类似,区别是在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用。')
})
//并且少了一个参数next(),不需要调用next进入
router.afterEach((to, from, next) => {
// ...
})
组件守卫
beforeRouteEnter((to, from, next) => {
console.log('进入组件之前')
})
beforeRouteLeave ((to, from, next) => {
console.log('离开组件之后')
})
beforeRouteUpdate((to, from, next) => {
console.log('该组件被复用时调用(2.2 新增)')
})
路由独享的守卫
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// ...
}
}
]
})
动态添加路由
//添加一条新路由规则。如果该路由规则有 name,并且已经存在一个与之相同的名字,则会覆盖它、原来的addRoutes 已经废弃
router.addRoute()