VUE 动态路由简单示例
store 中 permission.js
// import http from '@/utils/http';
// 导入组件(懒加载)
const loadView = (view) => (resolve) => require([`@/views/${view}`], resolve);
const loadLayout = (view) => (resolve) => require([`@/components/${view}`], resolve);
// 单个路由组装
const creatRoute = (item) => {
const newRoute = {};
newRoute.meta = {
title: 'test动态路由',
icon: item.icon,
id: item.id,
};
newRoute.path = item.url;
newRoute.component = loadView(item.component);
const keys = ['name', 'checkFlag', 'parentPermissionId', 'id'];
for (const key in item) {
if (keys.includes(key)) {
newRoute[key] = item[key];
}
}
return newRoute;
};
// 遍历后台传来的路由,转换为组件对象
const filterAsyncRouter = ({
item,
backRoutes = []
} = {}) => {
if (item.childList && item.childList.length > 0) {
const newItem = item.childList;
newItem.forEach((item) => {
filterAsyncRouter({
item,
backRoutes
});
});
} else {
backRoutes.push(creatRoute(item));
console.log('backRoutes', backRoutes)
}
return backRoutes;
}
// 把后台返回菜单组装成routes的格式
const getAsyncRoutes = (routes)=> {
let res = [];
routes.forEach((item) => {
res = res.concat(filterAsyncRouter({
item
}));
});
const temp = [{
path: '/',
component: Layout('layout')
redirect: '/manage',
children: []
}]
temp[0].children = res;
return temp;
}
const permission = {
state: {
addRoutes: [],
},
actions: {
// 请求权限树接口
generateRoutes({
commit
}) {
//(模拟数据)
const testTree = [{
checkFlag: false,
component: "",
icon: "",
id: 4,
name: "资源管理",
parentPermissionId: 1,
sort: null,
type: 5,
url: "parameter",
childList: [{
checkFlag: false,
childList: [],
component: "camera",
icon: "",
id: 5,
name: "摄像头",
parentPermissionId: 4,
sort: null,
type: 5,
url: "/camera",
}, {
checkFlag: false,
childList: [],
component: "algorithm",
icon: "",
id: 6,
name: "算法",
parentPermissionId: 4,
sort: null,
type: 5,
url: "/algorithm",
}]
}];
const asyncRoutes = getAsyncRoutes(testTree);
commit('SET_ADD_ROUTES', asyncRoutes);
return asyncRoutes
},
setAddRoutes: ({
commit
}, data) => {
commit('SET_ADD_ROUTES', data);
},
},
mutations: {
SET_ADD_ROUTES: (state, data) => {
state.addRoutes = data;
},
}
};
export default permission;
router.js
/* eslint-disable */
import Vue from "vue";
import Router from "vue-router";
import store from '@/store';
Vue.use(Router);
const VueRouterPush = Router.prototype.push;
Router.prototype.push = function push(to) {
return VueRouterPush.call(this, to).catch(err => err);
}
// 静态路由
export const constantRoutes = [{
path: "/login",
name: "login",
meta: {
title: '动态路由'
},
component: () => import( /* webpackChunkName: "login" */ "@/views/login.vue")
},
{
path: "/home",
name: "home",
component: () => import( /* webpackChunkName: "home" */ "@/views/home.vue")
}
]
const createRouter = () => new Router({
scrollBehavior: () => ({
y: 0
}),
routes: constantRoutes
})
const router = createRouter()
// 重置路由
export function resetRouter() {
const newRouter = createRouter()
router.matcher = newRouter.matcher // reset router
}
router.beforeEach(async (to, from, next) => {
// const token = Cookies.get('token');
// console.log("token", token)
// if (token) {
// // '动态添加路由'
// const addrouters = store.getters.getAddrouters;
// if (addrouters.length === 0) {
// const accessRoutes = await store.dispatch('generateRoutes');
// // router.options.routes = accessRoutes;
// router.addRoutes(accessRoutes);
// next({ ...to, replace: true });
// } else {
// next();
// }
// } else {
// if (to.path === '/login') {
// store.dispatch('setAddRoutes', []);
// next();
// } else {
// next('/login');
// }
// }
// '动态添加路由'
const addrouters = await store.getters.getAddrouters;
console.log('addrouters====', addrouters)
if (addrouters.length === 0) {
const accessRoutes = await store.dispatch('generateRoutes');
console.log('accessRoutes', accessRoutes)
router.addRoutes(accessRoutes);
next({
...to,
replace: true
});
} else {
next();
}
// if (to.path === '/login') {
// store.dispatch('setAddRoutes', []);
// next();
// } else {
// next('/login');
// }
});
export default router
store index.js
import Vue from 'vue';
import Vuex from 'vuex';
import getters from './getters';
import permission from './modules/permission';
// import createPersistedState from 'vuex-persistedstate';
Vue.use(Vuex);
const store = new Vuex.Store({
// plugins: [createPersistedState()],
getters,
modules: {
permission
}
});
export default store;
getters.js
const getters = {
getTest: state => state.test.msg,
getAddrouters: (state) => state.permission.addRoutes,
};
export default getters;