element-ui 路由动态加载功能

第一步 自定义默认的静态路由像登陆和首页这些一般开放的页面,主要代码如下:

	const router = new Router({
	  routes: [{
	    path: "/login/index",
	    component: () => import("../components/page/login/index.vue"),
	    meta: {
	      title: "登录",
	      keepAlive: true
	    }
	  }, {
	    path: "/",
	    redirect: "/index",
	    component: () => import("../components/page/index/index.vue"),
	    meta: {
	      title: "php平台开发"
	    },
	    children: [{
	      path: "/index",
	      component: () => import("../components/page/index/index.vue"),
	      name: "Home",
	      meta: {
	        title: "首页",
	        keepAlive: true
	      }
	    }]
	  }
	  ]
	});

第二步 在登录的时候从登陆接口获取的路由菜单数据保存到本地的localstorage里面

localStorage.setItem('adminRoutes', JSON.stringify(adminRoutes));    //adminRoutes是从登陆接口成功返回的路由菜单tree数据

第三步 在路由的文件中获取第二步保存的路由菜单数据动态添加路由

let adminRoutes = JSON.parse(localStorage.getItem('adminRoutes1'));
let route_data = [{
  path: "/login/index",
  component: () => import("../components/page/login/index.vue"),
  meta: {
    title: "登录",
    keepAlive: true
  }
}, {
  path: "/",
  redirect: "/index",
  component: () => import("../components/page/index/index.vue"),
  meta: {
    title: "广告投放平台"
  },
  children: [{
    path: "/index",
    component: () => import("../components/page/index/index.vue"),
    name: "Home",
    meta: {
      title: "首页",
      keepAlive: true
    }
  }]
}];


if(adminRoutes){
   adminRoutes.forEach(function (item, index) {
     let menu = item;
     let child_data = [];
     item.menu.forEach(function (item, index) {
       let children = item.children;
       children.forEach(function (item,index){
           let child_item =  {
                 path:item.path,
                 redirect:item.redirect,
                 component:() => import(`${item.component}`),
                 meta: {
                   title: "item.title",
                   keepAlive: true,
                   activeMenu: item.path
                 }
           };
           child_data.push(child_item)
       });
     });
     let topMenuRoute =  {
         path:item.rPath,
         redirect:item.redirect,
         component:() => import(`${item.component}`),
         children:child_data
     };
     route_data.push(topMenuRoute)
   })
}

坑一: component拼接问题


item1.component = '/user/index';
let child_item =  {
          path:item1.path,
          component: () => import(`../components/page/system${item1.component}.vue`),
          meta: {
            title: `${item1.title}`,
            keepAlive: true,
          }
};

//如上拼接写法没问题


item1.component = '/user/index/system';
let child_item =  {
          path:item1.path,
          component: () => import(`../components/page${item1.component}.vue`),
          meta: {
            title: `${item1.title}`,
            keepAlive: true,
          }
};

//这种写法就会出问题,不知道问题在哪,神奇




你可能感兴趣的:(elementui,vue,前端)