![在这里插入图片描述](https://img-blog.csdnimg.cn/3c43830ca98b494bb4f20945469c3a7f.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBALS3ljJfmtbfpgZPnmoTlpI_lpKnkuI3kvJror7Tlho3op4EtLQ==,size_19,color_FFFFFF,t_70,g_se,x_16)
**
function formatRouterTree(data) {
let parents = data.filter(p => p.pid === 0),
children = data.filter(c => c.pid !== 0);
dataToTree(parents,children);
function dataToTree(parents,children) {
parents.map((p) => {
children.map((c, i) => {
if(c.pid === p.id) {
let _c = JSON.parse(JSON.stringify(children));
_c.splice(i, 1);
dataToTree([c],_c);
if(p.children) {
p.children.push(c);
} else {
p.children = [c];
}
}
})
})
}
return parents;
}
function generateRouter(userRouters) {
let newRouters = userRouters.map((r) => {
let routes = {
path: r.path,
name: r.name,
component: () => import(`@/views/${r.name}`)
}
if(r.children) {
routes.children = generateRouter(r.children)
}
return routes;
})
return newRouters;
}
export {
formatRouterTree,
generateRouter
}
**
export default {
uid: 2,
hasAuth: false,
userRouters: []
}
**
import { getUserRouters } from "../services";
import { formatRouterTree } from "./index.js";
export default {
async setUserRouters ({ commit, state }) {
const userRouters = await getUserRouters(state.uid),
payload = formatRouterTree(userRouters);
commit('setUserRouters', payload);
commit('setAuth', true)
}
}
**
export default {
setAuth(state, auth) {
state.hasAuth = auth
},
setUserRouters(state, userRouters) {
state.userRouters = userRouters
}
}
**
import { generateRouter, formatRouterTree } from "@/libs/utils";
formatRouterTree.beforeEach((async(to, from, next) => {
if(!store.state.hasAuth) {
await store.dispatch('setUserRouters');
const newRoutes = generateRouter(store.state.userRouters);
router.addRoutes(newRoutes);
next({ path: to.path })
} else {
next();
}
}))
|