避免重复添加
var optData = JSON.parse(localStorage.getItem("optData"))||[];//路由数据
for(let i =0,length =optData.length;i++){
//箭头函数无法通过localStorage保存,所以后端返回路由数据后,前端要遍历添加文件的路径
optData[i].component=() => import(`@/views/HomePage${optData[i].path}.vue`)
//console.log(`@/views/HomePage/${optData[i].path}.vue`)
const element = optData[i];
//console.log('element==',element)
router.addRoute('HomePage',element);
}
拿到动态路由参数之后
let optData=[]//动态路由数据
//发送请求,后端根据用户返回路由数据,前端将其放入optData
//optData=res.data
localStorage.setItem('optData',JSON.stringify(optData))
for(let i =0,length =optData.length;i++){
optData[i].component=() => import(`@/views/HomePage${optData[i].path}.vue`)
const element = optData[i];
this.$router.addRoute('HomePage',element);
}
路由数据结构
const routes = [
{
path: '/Login',
name: 'Login',
component: () => import('@/views/Login.vue'),
meta: {
title: '登录',
},
},
{
path: '/',
name: 'homePage',
component: () => import('@/views/homePage.vue'),
redirect: '/homePage/xxx',//重定向要打开的页面
children: [
// ====================后端返回的数据结构=============================
{
path: '/homePage/xxx',
name: 'xxx',
component: () => import('@/views/homePage/xxx.vue'),//前端遍历添加
meta: {
title: '首页',
},
},
]
}
]