vue 路由守卫
路由前置守卫(全局)
-
to, 即将要进入的目标,路由对象
-
from, 当前导航正要离开的路由
-
next(需要填写函数) 当满足条件时放行
router.beforeEach((to, from, next) => {
if (to.path == "/user/cart") {
let token = localStorage.getItem("x-auth-token")
if (token) {
next()
} else {
alert("404")
}
} else {
next()
}
console.log("路由前置守卫", to, from);
})
路由局部守卫
-
因为是局部守卫,所以从哪来和要去哪都是固定的,所以可以直接调用next
{
path: '/user',
name: 'user',
component: () => import('../views/user.vue'),
beforeEnter: (to, from, next) => {
let token = localStorage.getItem("x-auth-token")
if (token) {
next()
} else {
alert("404")
//或调取提示组件的方法
}}
},
组件路由守卫
-
与methods同级,并且不需要写to from
export default {
data() { return {...};},
methods: {...},
beforeRouteEnter(to, from, next) {
let token = localStorage.getItem("x-auth-token")
if (token) {
next()
} else {
alert("404"),
//或调取提示组件的方法
}}};
路由守卫中调取提示组件的方法
-
因为路由守卫在创建期以前,没有this指向,所以需要使用 store.dispatch
store.dispatch("方法路径", {参数})
实例:
export default {标签:vue,else,守卫,token,localStorage,next,路由 From: https://www.cnblogs.com/Dollom/p/16943189.html
data() { return {...};},
methods: {...},
beforeRouteEnter(to, from, next) {
let token = localStorage.getItem("x-auth-token")
if (token) {
next()
} else {
//调取提示组件的方法
store.dispatch("showToast/asyncchangeisShowToast", {
show: true,
text: "请先登录!",
icon: "warning"
})
}}};