Vue3 导航守卫的使用方法

2025-01-10 20:12:24   小编

Vue3 导航守卫的使用方法

在 Vue3 开发中,导航守卫是一项强大的功能,它能帮助开发者在路由切换的不同阶段进行各种逻辑处理,极大地提升了应用的交互性与数据完整性。

导航守卫主要分为全局守卫、路由独享守卫和组件内守卫。

全局守卫作用于整个应用的路由切换过程。beforeEach 是最常用的全局守卫,它在每次路由切换前都会被调用。例如,我们可以用它来进行用户权限验证:

import { createRouter, createWebHistory } from 'vue-router';

const router = createRouter({
  history: createWebHistory(),
  routes: [
    // 路由配置
  ]
});

router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token');
  if (to.meta.requiresAuth &&!isAuthenticated) {
    next('/login');
  } else {
    next();
  }
});

export default router;

在上述代码中,通过检查 to.meta.requiresAuth 和用户是否已认证,决定是否跳转到登录页面。

beforeEnter 则是路由独享守卫,它直接定义在路由配置对象中。比如:

const routes = [
  {
    path: '/admin',
    name: 'admin',
    component: () => import('@/views/Admin.vue'),
    beforeEnter: (to, from, next) => {
      const isAdmin = localStorage.getItem('role') === 'admin';
      if (isAdmin) {
        next();
      } else {
        next('/');
      }
    }
  }
];

这段代码确保只有角色为 admin 的用户才能访问 /admin 页面。

组件内守卫定义在组件内部,如 beforeRouteEnterbeforeRouteUpdatebeforeRouteLeave。以 beforeRouteLeave 为例,它在离开当前组件对应的路由时触发,常用于提醒用户保存未完成的操作:

export default {
  name: 'EditPage',
  data() {
    return {
      formData: {}
    };
  },
  beforeRouteLeave(to, from, next) {
    if (Object.keys(this.formData).length > 0) {
      const confirmLeave = window.confirm('你有未保存的数据,确定离开吗?');
      if (confirmLeave) {
        next();
      } else {
        next(false);
      }
    } else {
      next();
    }
  }
};

通过合理运用这些导航守卫,我们可以灵活控制 Vue3 应用的路由导航逻辑,打造出更加健壮、易用的应用程序。

TAGS: Vue3 使用方法 导航守卫 Vue3导航守卫

欢迎使用万千站长工具!

Welcome to www.zzTool.com