使用导航守卫的全局前置守卫判断页面访问限制
1.在router中user页面也就是我的添加添加needLogin表示有token才能访问,如何没有打回到登录页面
2.代码如下
// 全局前置守卫
// to 去哪里 from 从哪里来 next是个函数调用即放行
router.beforeEach((to, from, next) => {
// 判断是否要去需要登录的页面
if (to.meta.needLogin) {
// 判断是否有token
if (store.state.user.token) {
// 放行
next()
} else {
// 没有token表示没登录 打回登录页
Toast('请登录')
next('/login')
}
} else {
// 不需要登录的页面,直接放行
next()
}
})
3.vue-router 3.1后增加的报错 把以下代码复制到 router 里即可
// 解决3.1版本后在控制台出现的警告
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
return originalPush.call(this, location).catch(err => err)
}
如果无效可能是多加了到layout中删除 replace
4.打回登录(login)页面携带user(我的页面)路径的参数让其登录直接跳转到该页面
改写成对象形式
next({
name: 'login',
query: {
back: to.path
}
})
来到login页面判断
// 登录成功要跳转 -- 有想去的页面就回到想去的页面,没有就去首页
if (this.$route.query.back) {
this.$router.push(this.$route.query.back)
} else {
this.$router.push('/')
}
ok!