用的是 全局前置守卫
在router实例中 加入 全局前置守卫 放入 要登录的路由的地址
router.beforeEach(to, from, next) to是要跳转的路由 from 是从那个路由跳转过来 next 是放行跳转 看看 跳转的路由中是否包含 要登录的路由地址 不包含 放行 包含 看看是否有token 有token 放行 没有 跳转登录页
详细的代码
// 全局前置守卫
const authUrl = ["/pay", "/myorder"] //需要token才能访问的页面数组
router.beforeEach((to, from, next) => {
// next()是否放行
// 如果next()调动 就是放行
// 如果next(路径)拦截到某个路径页面
if (!authUrl.includes(to.path)) {
// 非权限页面 直接放行
next()
return
}
// 是权限页面,判断是否有token
const token = store.getters.token
if (token) {
next()
} else {
next("/login")
}
})