技术共享

设置某些路由为公开访问,不需要登录状态即可访问

2024-07-08

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

在单页面应用(SPA)框架中,如Vue.js,路由守卫是一种非常有用的功能,它允许你控制访问路由的权限。Vue.js 使用 Vue Router 作为其官方路由管理器。路由守卫主要分为全局守卫和组件内守卫。

以下是如何设置路由守卫以允许某些路由公开访问的示例:

  1. 全局前置守卫:在Vue Router的配置中,你可以使用 beforeEach 方法设置一个全局前置守卫,来检查用户是否登录,并根据登录状态重定向用户。
// router/index.js
import Vue from 'vue';
import Router from 'vue-router';
import Home from '../components/Home.vue';
import Dashboard from '../components/Dashboard.vue';

Vue.use(Router);

const router = new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home
    },
    {
      path: '/dashboard',
      name: 'Dashboard',
      component: Dashboard,
      meta: {
        requiresAuth: true // 标记需要认证的路由
      }
    }
    // 其他路由...
  ]
});

// 全局前置守卫
router.beforeEach((to, from, next) =