vue3 动态路由生成
动态路由生成----vue3
stores/index.js
import { defineStore } from 'pinia';
export const useRouteStore = defineStore('route', {
state: () => ({
dynamicRoutes: false
})
});
router/index.js
import {createRouter, createWebHistory} from 'vue-router'
import HomeView from '../views/HomeView.vue'
import UserView from '../views/UserView.vue'
import axios from 'axios';
import {useRouteStore} from '../stores/index.js';
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: HomeView,
children: [
{
path: '/user',
name: 'user',
component: UserView,
},
],
}
], // 使用 generateRoutes() 函数生成路由配置
});
// 在路由实例创建后再调用 generateRoutes() 函数
router.beforeEach(async (to, from, next) => {
const store = useRouteStore()
if (!store.dynamicRoutes) {
await generateRoutes();
store.dynamicRoutes = true
next({...to, replace:true});
} else {
next();
}
});
async function generateRoutes() {
// 异步请求获取动态路由数据
const dynamicRoutesData = await fetchDynamicRoutesData();
// 根据获取到的数据生成动态路由
const dynamicRoutes = await generateDynamicRoutes(dynamicRoutesData);
dynamicRoutes.forEach(route => {
router.addRoute('home', route); // 将动态生成的路由添加到 'home' 路由的 children 数组中
});
}
async function fetchDynamicRoutesData() {
// 发起异步请求获取动态路由数据
try {
const response = await axios.get('http://127.0.0.1:8000/api/v1/permission/menu/', {
headers: {
'token': localStorage.getItem("token")
}
});
return response.data.results;
} catch (error) {
console.error('Failed to fetch dynamic routes data:', error);
return []; // 返回一个空数组以避免生成动态路由时报错
}
}
async function generateDynamicRoutes(dynamicRoutesData) {
// 根据动态路由数据生成路由配置数组
const dynamicRoutes = [];
for (const menu of dynamicRoutesData) {
if (menu.children) {
for (const e of menu.children) {
// 动态导入组件
const component = await import(`../views/${e.component}.vue`);
// 转成路由
let route = {
name: e.name,
path: e.path,
component: component.default,
meta: {
icon: e.icon,
title: e.title
}
};
// 将路由添加到动态路由数组中
dynamicRoutes.push(route);
}
}
}
return dynamicRoutes;
}
export default router;