Dynamic routing permissions are an essential feature when we are developing a large front-end application. This article will explain how to use Vue 3 and TypeScript to implement dynamic routing permissions and keep performance at the best.
1. Pre-knowledge
Before you start, you need to have a basic understanding of the following:
- Vue 3
- TypeScript
- Vue Router
2. Implementation ideas
The implementation idea of dynamic routing permissions can be divided into the following steps:
- Create a route guard to determine whether the route needs permission verification before entering the route.
- Add in routing configuration
meta
Fields to mark the permission verification required for the route, as well as the permission information required for the route. - Create a permission verification function to determine whether you have permission to access the route based on the current user's role and the permission information of the route.
- Call the backend API in the permission verification function to obtain the role information of the current user and save the information to Vuex state management.
- Call the permission verification function in the route guard and perform corresponding operations based on the verification results, such as jumping to the login page or displaying an unauthorized access prompt.
3. Specific implementation
The following will introduce how to use Vue 3 and TypeScript to implement dynamic routing permissions.
3.1 Create a route guard
First, we need to create a global route guard to determine whether the route needs permission verification. existrouter/
Add the following code to:
import { router } from './index'; import store from '../store'; ((to, from, next) => { if ((record => )) { const hasToken = ['auth/hasToken']; if (!hasToken) { // Jump to login page next('/login'); return; } const requiredRoles = ; const userRole = ['user/role']; if (!(userRole)) { // Show unauthorized access prompt next('/403'); return; } } next(); });
In the above code, we first determine whether the route needs permission verification. If necessary, we will determine whether the current user has a token. If not, we will jump to the login page; then we will determine whether the route has permission to access the route based on the role of the current user and the permission information required by the route. If not, a prompt for unauthorized access is displayed.
3.2 Add routing meta information
Next, addmeta
Fields to mark the permission verification required for the route, as well as the permission information required for the route. existrouter/
Add the following code to:
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'; const routes: RouteRecordRaw[] = [ { path: '/login', name: 'Login', component: () => import('../views/'), }, { path: '/', name: 'Home', component: () => import('../views/'), meta: { requiresAuth: true, roles: ['admin', 'editor'], }, }, { path: '/about', name: 'About', component: () => import('../views/'), meta: { requiresAuth: true, roles: ['admin'], }, }, // ... ]; export const router = createRouter({ history: createWebHistory(), routes, });
In the above code, we added in the routing configurationmeta
Fields to define permission verification required for the route and the permission information required for the route.
3.3 Create permission verification function
Next, we need to create a permission verification function to determine whether the current user has permission to access the route. existstore/modules/
Add the following code to:
import { Module } from 'vuex'; import { RootState } from '../index'; interface UserState { id: number; role: string; } const userModule: Module<UserState, RootState> = { namespaced: true, state: { id: 0, role: '', }, getters: { role(state): string { return ; }, }, mutations: { setId(state, id: number) { = id; }, setRole(state, role: string) { = role; }, }, actions: { async fetchUser({ commit }) { // Call the backend API to get the role information of the current user const response = await fetch('/api/user'); const data = await (); commit('setId', ); commit('setRole', ); }, }, }; export default userModule; export type { UserState };
In the above code, we first define aUserState
Interface to describe user status; thenuserModule
Define afetchUser
Asynchronous action calls the backend API to obtain the role information of the current user and save the information to Vuex state management.
3.4 Calling permission verification function
Finally, call the permission verification function in the route guard and perform corresponding operations based on the verification results. existrouter/
Add the following code to:
import { router } from './index'; import store from '../store'; (async (to, from, next) => { if ((record => )) { const hasToken = ['auth/hasToken']; if (!hasToken) { // Jump to login page next('/login'); return; } const requiredRoles = ; const userRole = ['user/role']; if (!userRole) { // Get the role information of the current user await ('user/fetchUser'); } if (!(userRole)) { // Show unauthorized access prompt next('/403'); return; } } next(); });
In the above code, we first determine whether the route needs permission verification. If necessary, we will determine whether the current user has a token. If not, we will jump to the login page; then we will determine whether the route has permission to access the route based on the role of the current user and the permission information required by the route. If not, a prompt for unauthorized access is displayed. When we first access a route that requires permission verification, we will callfetchUser
Asynchronous action to obtain the role information of the current user and save the information to Vuex state management.
4. Performance optimization
To maintain optimal performance, we can optimize dynamic routing permissions using the following methods:
- Cache user information: After the user logs in, we can cache the current user's role information in local storage or cookies to reduce unnecessary API calls.
- Lazy Load Routing: Use lazy loading dynamically load routing components in routing configurations to reduce initial loading time and reduce page burden.
- Using routing cache: Use routing cache in routing components that require permission verification to reduce duplicate rendering of components and improve page response speed.
This is the introduction to this article about the examples of Vue3+TS implementing dynamic routing permissions. For more related content on Vue3 dynamic routing permissions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!