Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
// src/router/index.ts (guards section) import { createRouter, createWebHistory } from 'vue-router'; import { useAuthStore } from '@/stores/auth'; const router = createRouter({ history: createWebHistory(), routes: [ { path: '/login', name: 'login', component: () => import('../views/LoginView.vue') }, { path: '/dashboard', name: 'dashboard', component: () => import('../views/DashboardView.vue'), meta: { requiresAuth: true, title: 'Dashboard' } }, { path: '/admin', name: 'admin', component: () => import('../views/AdminView.vue'), meta: { requiresAuth: true, roles: ['admin'] } }, ], }); // Global before guard router.beforeEach((to, from) => { const auth = useAuthStore(); if (to.meta.requiresAuth && !auth.isLoggedIn) { return { name: 'login', query: { redirect: to.fullPath } }; } if (to.meta.roles && !to.meta.roles.includes(auth.role)) { return { name: 'dashboard' }; // redirect unauthorised } }); // Set document title router.afterEach((to) => { document.title = to.meta.title ? `${to.meta.title} | MyApp` : 'MyApp'; }); export default router;
Result
Open