Vue2 动态路由

VUE CLI 项目

router.js

import Vue from "vue";
import Router from "vue-router";
import base from "@/view/404/404.vue";

const originalPush = Router.prototype.push
Router.prototype.push = function push (location) {
    
    
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(Router);

//配置路由
const router = new Router({
    
    
  // mode: "history",
  mode: "hash",
  routes: [
    {
    
    
      path: "/",
      name: "Login",
      component: () => import("@/view/login.vue"),
    },
    {
    
    
      path: "/Layout",
      name: "Layout",
      component: () => import("@/view/layout.vue")
    },
    {
    
    
      path: '/404',
      name: 'base',
      component: base
    }

  ],
});

//导出
export default router;

main.js


var getRouter //用来获取后台拿到的路由
router.beforeEach((to, from, next) => {
    
    
  if (!getRouter) {
    
     //不加这个判断,路由会陷入死循环
    if (to.path == '/' || to.path == '/Layout') {
    
    
      if(to.path == "/"){
    
    
        Vue.prototype.nativeplacestore.clear()
      }
      next()
    } else {
    
    
      if (!Vue.prototype.nativeplacestore.get("uu")) {
    
    
        next()
      } else {
    
    
        getRouter = Vue.prototype.nativeplacestore.get("uu")
        getRouter.map(x=>{
    
    
          router.addRoute("Layout",{
    
    
            path: "/Layout/"+x.path,
            name: "Path"+x.path,
            component: () => import("@/view/1.vue"),
            children:[]
          })
          return {
    
    
            path: "/Layout/"+x.path,
            name: "Path"+x.path,
            component: () => import("@/view/1.vue"),}}
        )

        if(Vue.prototype.nativeplacestore.get("WenShiDu")){
    
    
          router.addRoute("Layout",{
    
    
            path: "/Layout/WenShiDu",
            name: "WenShiDu",
            component: () => import("@/view/2.vue"),
            children:[]
          })
        }

        router.addRoute(
            {
    
    
              path: '*',
              redirect: "/404",
            }
        )
        next({
    
    
          ...to,
          replace: true
        })
      }
    }
  } else {
    
    
    next()
  }
})

猜你喜欢

转载自blog.csdn.net/weixin_45381071/article/details/138676841