Vue 路由保卫

打印 上一主题 下一主题

主题 1514|帖子 1514|积分 4542

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x

一、全局路由保卫 router.js

1. 前置保卫

  1. router.beforeEach((to, from, next) => {
  2.   // to: Route 即将要进入的目标 路由对象
  3.   // from: Route 当前导航正要离开的路由
  4.   // next: Function 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
  5.   // 例如,验证用户是否已登录
  6.   if (to.matched.some(record => record.meta.requiresAuth)) {
  7.     if (!auth.isLoggedIn()) {
  8.       next({
  9.         path: '/login',
  10.         query: { redirect: to.fullPath }
  11.       });
  12.     } else {
  13.       next();
  14.     }
  15.   } else {
  16.     next(); // 确保一定要调用 next()
  17.   }
  18. });
复制代码
2. 后置钩子

  1. router.afterEach((to, from) => {
  2.   // to: Route 即将要进入的目标 路由对象
  3.   // from: Route 当前导航正要离开的路由对象
  4.   // 全局后置钩子,不会接受 next 函数也不会改变导航本身
  5.   if (to.meta.title) {
  6.     document.title = to.meta.title + " - 系统名称"
  7.   }
  8.   console.log('Navigation completed successfully.');
  9. });
复制代码

二、路由独享的保卫

  1. const router = new VueRouter({
  2.   routes: [
  3.     {
  4.       path: '/foo',
  5.       component: Foo,
  6.       beforeEnter: (to, from, next) => {
  7.         // 参数和全局前置守卫类似
  8.       }
  9.     }
  10.   ]
  11. });
复制代码

三、组件内的保卫

可以在路由组件内直接定义以下三个路由保卫:
  1. beforeRouteEnter
  2. beforeRouteUpdate (2.2+ 支持)
  3. beforeRouteLeave
复制代码
示例:beforeRouteEnter 保卫
  1. export default {
  2.   name: 'UserProfile',
  3.   beforeRouteEnter(to, from, next) {
  4.     // 在渲染该组件的对应路由被 confirm 前调用
  5.     // 不能获取组件实例 `this` 组件实例尚未创建
  6.     next(vm => {
  7.       // 通过 `vm` 访问组件实例
  8.     });
  9.   },
  10.   beforeRouteLeave(to, from, next) {
  11.     // 导航离开该组件的对应路由时调用
  12.     // 可以访问组件实例 `this`
  13.     const answer = window.confirm('Do you really want to leave? you have unsaved changes!');
  14.     if (answer) {
  15.       next(); // 确保调用 next() 方法,否则钩子就不会被 resolved。
  16.     } else {
  17.       next(false); // 使用 'next(false)' 来取消导航并停留在当前页面。或者可以使用 'next('/')' 或者 'next(new Location)' 来跳转到不同的地址。
  18.     }
  19.   }
  20. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

干翻全岛蛙蛙

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表