通过to.name 来限制:在router 的 index.js 路由页面设置
// 路由导航守卫 ==>全局守卫
router.beforeEach((to, from, next) => {
let nextRoute = ["Cartlist", "MyPath", "List"] // 被限制的 路由地址 【购物车 地址管理 分类】
console.log(nextRoute.indexOf(to.name));
let loginData = JSON.parse(localStorage.getItem(
if (nextRoute.indexOf(to.name) >= 0) {
// 判断是否登录
if (!loginData) {
router.push(
}
}
next()
})
每个守卫方法接收三个参数:
to: Route: 即将要进入的目标 路由对象
from: Route: 当前导航正要离开的路由
next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。
next(false): 中断当前的导航。如果浏览器的 URL 改变了 (可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。
next(
next(error): (2.4.0+) 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。