全局前置钩子router.beforeEach(fn),导航被触发----一般登录验证 全局解析钩子router.beforeResolve(fn),组件初始化 全局后置钩子router.afterEach(fn),没有next,导航被确认,一般路由跳转以后用window把窗口调上去
//全局前置守卫
router.beforeEach((to, from, next) => {
//用户未登录只能访问首页、登录注册页面
if (to.path == "/" || to.path == "/login" || to.path == "/register") {
next();
} else {
//去其他页面判断是否登录
let flag = window.localStorage.getItem("email");
//登录过直接放行
if (flag) {
next()
} else {
//未登录则跳转到首页
Message({
message: '您尚未登录哦,请先登录!',
type: 'warning',
duration: 1500
});
next("/");
}
}
})
//全局后置守卫 比如一个组件滑动到页面中间 下一个组件需要初始化组件,必须设置到初始位置
router.afterEach((to, from) => {
window.scrollTo(0,0)
})
路由独享的守卫
路由独享的守卫beforeEnter(to,from,next),路由初始化(组件未初始化)----
a,路由鉴权-----用户体验:界面,功能,bug,效率,权限
b,组件异步加载情景中(插件配置:syntax-dynamic-import)
routes:[{
path:"/test",
component:()=>import("../components/Test.vue"),
beforeEnter(to,from,next){
if(to.path==="/test"){
alert("请登录");
next(false); // 禁止跳转
}else{
next()
}
}