vue router官网:
导航守卫 | Vue RouterVue.js 的官方路由https://router.vuejs.org/zh/guide/advanced/navigation-guards
Vue 路由守卫包括全局前置守卫(beforeEnter)、路由实例方法和命名空间相关的守卫(beforeEnter、enter、update、leave)。它们的功能和使用方法如下:
- 全局前置守卫(beforeEnter):在导航到新的路由之前执行,可以用来控制导航。例如,检查用户是否已登录,如果未登录则重定向到登录页面。使用方法:在router.beforeEach钩子中定义一个函数,该函数接收next、to、from三个参数,next()表示进行管道中的下一个钩子(to),to表示即将要进入的目标路由对象,from表示当前导航正要离开的路由。
- 路由实例方法守卫(beforeEnter、enter、update、leave):和全局守卫的用法类似,可以控制导航和进行一些业务处理。使用方法:在路由对象的beforeEnter、enter、update、leave属性中定义一个函数,这些函数会在路由的实例上被调用,接收to、from、next三个参数。例如,在路由对象的beforeEnter属性中定义一个函数,该函数会在这个路由被访问之前被执行。
- 命名空间相关的守卫(beforeEnter、enter、update、leave):基于命名空间来控制导航。使用方法:在路由对象的beforeEnter、enter、update、leave属性中定义一个函数,这些函数会在对应命名空间的路由被访问之前或之后被执行。例如,在一个具有命名空间的路由上定义一个leave守卫,当导航离开这个路由时,该守卫会被执行。
总之,Vue 路由守卫可以用来控制导航、进行一些业务处理以及在路由实例上执行特定操作。在定义路由守卫时,需要注意参数的使用和调用顺序。
一.全局前置守卫
全局前置守卫是用来做什么的呢?
当你登录页面时,调用这个,使你的页面能够跳转。当你未登录时,不跳转。
先创建一个用来存放代码的js文件
进行代码撰写。
先加载vue-router:
npm install vue-router@4
在permission.js中写下代码:
//处理权限验证相关的东西
import router from '~/router'
import { toast } from '~/composables/util.js'
import { getToken } from '~/composables/auth'
//全局前置守卫
router.beforeEach((to, from, next) => {
// console.log(to);
// console.log(from);
const token = getToken()
//如果没有登录强制跳转会登录页
if (!token && to.path != "/") {
toast("请先登录","error")
return next({ path:"/" })
}
//防止重复登录
if(token && to.path == "/"){
toast("请勿重复登录","error")
return next({ path:from.path ? from.path : "/" })
}
next();
// console.log("全局前置守卫");
});
在main.js中应用它:
二.随便记录一下其他封装方法
toast
import { ElNotification } from 'element-plus'
//消息提示的方法
export function toast(message, type = "success",dangerouslyUseHTMLString=false) {
ElNotification({
message,
type,
duration:4000,
dangerouslyUseHTMLString
})
}
cookies
//cookies封装
import { useCookies } from '@vueuse/integrations/useCookies'
const TokenKey = 'user-token'
const cookies = useCookies()
//获取token
export function getToken(){
return cookies.get(TokenKey)
}
//设置token
export function setToken(token){
return cookies.set(TokenKey,token)
}
//清楚token
export function deleteToken(){
return cookies.remove(TokenKey)
}