网站首页 > 精选文章 正文
参考官网: https://router.vuejs.org/zh/guide
- 路由守卫种类:三大全局路由守卫,三大组件路由守卫,一个路由独享守卫
- 使用位置:全局和独享在路由文件 src\router\index.js,组件守卫在组件中
- 相关参数
to :要跳转到的目标路由信息
from:跳转前的路由信息
next():不传参执行下一步,传false阻断程序执行,传 { path: '路径' } 或者 { name: "Login" } 跳转到目标路由
1. 三大全局路由守卫
全局守卫使用前需要修改下路由文件,否则就得拿到 main.js 中配置全局守卫
使用全局守卫必须获取路由实例化对象
const routes = [] // 路由对象在此配置
const router = new Router({
routes
});
/******** 在此区域配置路由全局守卫 **********/
export default router;
全局路由守卫先执行,组件生命周期后执行
使用位置:路由文件 src\router\index.js
// 全局前置守卫
// 在页面加载之前执行,在所有守卫和生命周期之前执行,优先级第一
// 不使用 next()方法 会阻断程序
router.beforeEach((to, from, next) => {
console.log("beforeEach", to, from);
to.meta.requireAuth = false;
//判断该路由是否需要登录权限
if (to.meta.requireAuth) {
if (cookies("token")) {
next();
} else {
next({
path: "/login",
query: { redirect: to.fullPath }
// 保存要跳转的目标路由,登录成功后跳转到该路由
});
}
} else {
next();
}
});
// 全局解析守卫
// 在beforeEach之后执行
// 不使用 next()方法 会阻断程序
router.beforeResolve((to, from, next) => {
console.log("beforeResolve", to, from);
next();
});
// 全局后置守卫
// 在beforeResolve之后执行
// 没有next()
router.afterEach((to, from) => {
console.log("afterEach", to, from);
});
2. 一大路由独享守卫
使用位置:路由文件 src\router\index.js 路由对象中
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
console.log("beforeEnter", to, from);
next()
}
}
]
3. 三大组件内守卫
在组件中使用
// 进入组件时执行
// 不!能!获取组件实例 `this`
beforeRouteEnter (to, from, next) {
console.log("beforeRouteEnter ", to, from);
next();
},
// 在当前路由改变,但是该组件被复用时调用
// 可以访问组件实例 `this`
beforeRouteUpdate (to, from, next) {
console.log("beforeRouteUpdate ", to, from);
next();
},
// 导航离开该组件的对应路由时调用
// 可以访问组件实例 `this`
beforeRouteLeave (to, from, next) {
console.log("beforeRouteLeave ", to, from);
next();
},
4. 路由守卫执行的先后顺序
导航被触发。
在失活的组件里调用 beforeRouteLeave 守卫。
调用全局的 beforeEach 守卫。
在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+)。
在路由配置里调用 beforeEnter。
解析异步路由组件。
在被激活的组件里调用 beforeRouteEnter。
调用全局的 beforeResolve 守卫 (2.5+)。
导航被确认。
调用全局的 afterEach 钩子。
触发 DOM 更新。
调用 beforeRouteEnter 守卫中传给 next 的回调函数,创建好的组件实例会作为回调函数的参数传入。
- 上一篇: React 对比 Vue 如何做路由鉴权?
- 下一篇: Vue路由配置方法详细介绍
猜你喜欢
- 2024-12-29 前端vue与后端Thinkphp在服务器的部署
- 2024-12-29 第03节:创建登陆页
- 2024-12-29 详解Nginx代理Vue3项目的实践与配置
- 2024-12-29 React/Vue路由全攻略:鉴权、导航守卫与拦截,让你站在技术之巅
- 2024-12-29 Vue3.2项目架构详解
- 2024-12-29 vue项目本地开发完成后部署到服务器后报404是什么原因呢?
- 2024-12-29 Vue路由配置方法详细介绍
- 2024-12-29 React 对比 Vue 如何做路由鉴权?
- 2024-12-29 vue3 动态组件使用技巧
- 2024-12-29 Vue3.0权限管理实现流程【实践】
- 最近发表
- 标签列表
-
- 向日葵无法连接服务器 (32)
- git.exe (33)
- vscode更新 (34)
- dev c (33)
- git ignore命令 (32)
- gitlab提交代码步骤 (37)
- java update (36)
- vue debug (34)
- vue blur (32)
- vscode导入vue项目 (33)
- vue chart (32)
- vue cms (32)
- 大雅数据库 (34)
- 技术迭代 (37)
- 同一局域网 (33)
- github拒绝连接 (33)
- vscode php插件 (32)
- vue注释快捷键 (32)
- linux ssr (33)
- 微端服务器 (35)
- 导航猫 (32)
- 获取当前时间年月日 (33)
- stp软件 (33)
- http下载文件 (33)
- linux bt下载 (33)