项目需求:除固定的模块使用静态路由定义外,其他路由由后端定义配置后,以接口的形式返回给前端动态添加。这里使用 vue-router addRoutes 方法操作。
具体实现方式如下:
// main.js
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import Antd from "ant-design-vue";
import "ant-design-vue/dist/antd.css";
Vue.config.productionTip = false;
Vue.use(Antd);
// 路由监听
router.beforeEach((to, from, next) => {
// 统一处理动态路由
const UpdateRoutes = () => {
// 获取动态路由
const routeArr = [
{
path: "/demo",
name: "Demo",
templatePath: "./views/Demo.vue",
title: "Demo管理",
children: [
{
path: "/list",
name: "DemoList",
templatePath: "./views/DemoList.vue",
title: "Demo列表",
children: [],
meta: {}
}
],
meta: {}
},
{
path: "/test",
name: "Test",
templatePath: "./views/Test.vue",
title: "Test管理",
children: [],
meta: {}
}
];
sessionStorage.routeArr = JSON.stringify(routeArr);
let data = JSON.parse(sessionStorage.routeArr);
// 统一处理组件路由关联解析
const templateAnalysis = data => {
data.forEach(item => {
item.component = () => import(`${item.templatePath}`);
if (item.children.length > 0) {
templateAnalysis(item.children);
}
});
};
templateAnalysis(data);
// 本地存储
store.commit("setRoutes", data);
// 加载动态路由
router.addRoutes(store.state.routes);
};
// 处理页面刷新与路由切换
if (!from.name) {
console.log("页面刷新");
if (
router.options.routes.filter(item => item.name === to.name).length !== 0
) {
UpdateRoutes();
console.log("静态路由");
} else {
if (!to.name) {
UpdateRoutes();
console.log("动态路由");
router.push(to.path);
}
}
} else {
console.log("路由切换");
}
next();
});
router.afterEach(() => {});
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");
// router.js
import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "Index",
component: () =>
import(/* webpackChunkName: "index" */ "../views/Index.vue")
},
{
path: "/home",
name: "Home",
component: () => import(/* webpackChunkName: "home" */ "../views/Home.vue")
},
{
path: "/about",
name: "About",
component: () =>
import(/* webpackChunkName: "about" */ "../views/About.vue")
},
{
path: "/list",
name: "List",
component: () => import(/* webpackChunkName: "list" */ "../views/List.vue")
}
];
const router = new VueRouter({
routes
});
export default router;
// store.js
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
routes: [] // 动态路由
},
mutations: {
setRoutes(state, payload) {
state.routes = payload;
}
},
actions: {},
modules: {}
});
注:主要注意以下几点:
- 需要判断页面是刷新还是路由切换,便于操作动态路由,避免重复添加
- 动态路由刷新后,需要进行二次跳转,以实现组件加载
- 动态路由的定义要符合 router 的数据结构。