2024-07-08
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
In single page application (SPA) frameworks, such as Vue.js, route guards are a very useful feature that allows you to control access to routes. Vue.js uses Vue Router as its official route manager. Route guards are mainly divided into global guards and component guards.
Here is an example of how to set up route guards to allow certain routes to be publicly accessible:
beforeEach
The method sets a global pre-guard to check whether the user is logged in and redirect the user based on the login status.// 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) =