目标
- 编程式导航
- 路由监听
- 导航守卫
编程式导航
https://router.vuejs.org/zh/guide/essentials/navigation.html
该方法的参数可以是一个字符串路径,或者一个描述地址的对象。例如:
image.png
路由监听
通过watch属性设置监听$route变化,达到监听路由跳转的目的。
在App.vue里增加如下代码
watch: {
// 监听路由跳转。
$route(newRoute, oldRoute) {
console.log('watch', newRoute, oldRoute)
},
}
页面切换时观察console
image.png导航守卫
全局导航守卫
全局导航守卫要在main.js 里写导航守卫逻辑
类似这样:
router.beforeEach(function(to, from, next) {
let flag = sessionStorage.getItem("flag");
//如果登录标志存在用为isLogin
if(flag==='isLogin'){
next()
//如果已经登录,还想进入登录界面,则定向到首页
if(!to.meta.auth){
next({
path: '/index'
})
}
}else{
//如果用户未登录想进入需要登录的界面,则重定向到登录页
if(to.meta.auth){
next({
path: '/login'
})
}else{//如果不需要验证,则直接放行
next()
}
}
});
目前我们先简单了解,
在main.js里我们先写如下代码,然后断点看
router.beforeEach(function(to, from, next) {
console.log(from);
console.log(to);
});
image.png
每个守卫方法接收三个参数:
-
to: Route
: 即将要进入的目标 路由对象 -
from: Route
: 当前导航正要离开的路由 -
next: Function
: 一定要调用该方法来 resolve 这个钩子。执行效果依赖next
方法的调用参数。-
next()
: 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。 -
next(false)
: 中断当前的导航。如果浏览器的 URL 改变了 (可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到from
路由对应的地址。 -
next('/')
或者next({ path: '/' })
: 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。你可以向next
传递任意位置对象,且允许设置诸如replace: true
、name: 'home'
之类的选项以及任何用在router-link
的to
prop 或router.push
中的选项。 -
next(error)
: (2.4.0+) 如果传入next
的参数是一个Error
实例,则导航会被终止且该错误会被传递给router.onError()
注册过的回调。
-
确保要调用 next
方法,否则钩子就不会被 resolved。
类别
1、全局守卫 router.beforeEach((to, from, next) => {}) router.beforeResolve((to, from, next) => {}) router.afterEach((to, from) => {})
2、路由守卫 beforeEnter(to, from, next) {}
3、组件内守卫 beforeRouteEnter(to, from, next) {} beforeRouteUpdate(to, from, next) {} beforeRouteLeave(to, from, next) {}
路由跳转时守卫的运行顺序如下:##
进入一个新路由 beforeEach => beforeEnter => beforeRouteEnter => beforeResolve => afterEach
当前路由下跳转,如替换路由参数 beforeEach => beforeRouteUpdate => beforeResolve => afterEach
离开当前路由 beforeRouteLeave => beforeEach => beforeResolve => afterEach
网友评论