vue 路由动态添加 动态文件

2022-12-31 14:49:57

1vue -router 数据是存在缓存中,存在刷新丢失(类似vuex),router 添加路由在 路由守卫里统一处理;

1.登录->添加路由->刷新丢失->路由登录前->添加—>统一 路由守卫是添加(大一统)


import Main from "@/components/main";
// 配置 按钮
import config from "@/config";
const { isbnt } = config;

// 代理到vux
import store from "@/store";

export let initroute = function(arr) {
  let routes = [],
    butList = [];
  routes = arr.map((item, index) => {
    // 处理路由 button
    if (item.component.indexOf("/") == -1 && item.webPath.indexOf("/") == -1) {
      butList.push(item);
    }

    return {
      path: item.webPath,
      name: item.name,
      meta: {
        icon: item.icon,
        title: item.description,
        // 隐藏菜单
        hideInMenu: item.routerType == "otherRouter"
      },
      component: Main,
      children: item.children.map((oitem, index) => {
        // 路由处理
        let o_component;
        if (oitem.component.indexOf("_c") != -1) {
          oitem.component = oitem.component.replace("_c/cwl", "");
          o_component = import(`_c/cwl${oitem.component}`);
        } else if (oitem.component.indexOf("cwl") != -1) {
          oitem.component = oitem.component.replace("@/view/cwl", "");
          o_component = import(`@/view/cwl${oitem.component}`);
          console.log(oitem.children, "=========oitem.children");
        } else if (oitem.component.indexOf("nutrition") != -1) {
          oitem.component = oitem.component.replace("@/view/nutrition", "");
          o_component = import(`@/view/nutrition${oitem.component}`);
        } else if (oitem.component.indexOf("home") != -1) {
          oitem.component = oitem.component.replace("@/view/home", "");
          o_component = import(`@/view/home${oitem.component}`);
        } else if (oitem.component.indexOf("detectassess") != -1) {
          oitem.component = oitem.component.replace("@/view/detectassess", "");
          o_component = import(`@/view/detectassess${oitem.component}`);
        } else if (oitem.component.indexOf("monitoring-center") != -1) {
          oitem.component = oitem.component.replace(
            "@/view/monitoring-center",
            ""
          );
          o_component = import(`@/view/monitoring-center${oitem.component}`);
        }

        if (
          oitem.component.indexOf("/") == -1 &&
          oitem.webPath.indexOf("/") == -1
        ) {
          butList.push(oitem);
        }

        // 按钮 设置
        oitem.children.forEach((zitem, zindex) => {
          if (
            zitem.component.indexOf("/") == -1 &&
            zitem.webPath.indexOf("/") == -1
          ) {
            butList.push(zitem);
          }
        });

        let children = {
          path: oitem.webPath,
          name: oitem.name,
          meta: {
            icon: item.icon,
            title: oitem.description
          },
          component: () => o_component
        };

        // 隐藏菜单
        if (oitem.routerType == "otherRouter") {
          children.meta.hideInMenu = true;
        }
        return children;
      })
    };
  });
  console.log(routes, "=====================routes123", butList);
  if (Array.isArray(butList) && butList.length > 0) {
    let isbntarr = [];
    butList.forEach(item => {
      if (item.name in isbnt) {
        isbntarr.push(isbnt[item.name]);
      }
    });
    console.log(isbntarr, "===123");
    window.sessionStorage.setItem("isbntList", JSON.stringify(isbntarr));
  }
  return routes;
};

    let routingArray = initroute(JSON.parse(response.respBody));
              routes.push(...routingArray);
              router.addRoutes(routes);

路由刷新会丢失 类似于 vuex 的数据结构 因此需要重新赋值 添加
参考vuex :https://editor.csdn.net/md/?articleId=118481831

  let routelist = sessionStorage.getItem("routelist");
  let routingArray = initroute(JSON.parse(routelist));
  routes.push(...routingArray);
  router.addRoutes(routes);

动态文件


        
// ----------------------------------------------------------------------------------
        res = "huizhou/huizhou";
        let huizhou = require(`@/assets/map/${res}.json`);
        echarts.registerMap("huizhou", huizhou as any);
//  json 可以进行ajax请求进行处理文件
       

参考:https://www.jianshu.com/p/386916c73dad

       res = "huizhou/huizhou";
        let huizhou = import(`@/assets/map/${res}.json`);
        console.log(huizhou, "======================import");
        huizhou.then((res) => {
          console.log(res.default, "===res");
        });

让我们来分析一下:第一个不同寻常的地方在于-我们引入a.js两次,然而只得到了一次反馈。你可能还记得,这是ES模块的一个特性,当他们为单例时,他们只被调用一次。
其次,动态导入在静态导入之前执行。这是因为我在我的HTML中引入了传统的脚本中调用了动态import()(你也可以在传统的脚本中使用动态导入,不仅仅是在模块中!):

<script type="module" src="static.js"></script>
<script src="dynamic.js"></script>

我们知道type="module"脚本会默认延迟,等到DOM解析后才会按顺序被引入进来。这就是为什么dynamic脚本先被执行。熟练运用import()会让你找到一把打开所有原生ES模块的一把钥匙,你可以随时随地的加载并使用他们。
第三个不同在于:静态导入保证你的脚本按顺序执行, 但是动态导入的脚本不按它们在代码中显示的顺序执行。你必须知道,每一个动态导入都是独立存在的,他们之间互无关联,也不会等待其他执行完成执行。

动态import()提供基于Promise的API
import()遵循ES模块规则:单例、匹配符、CORS 等
import()可以在传统的脚本中使用也可以在模块中使用
在代码中使用的import()的顺序与它们被解析的顺序没有任何关联

<!--module.js-->
<script type="module" src="module.js"></script>

<!--classic.js-->
<script src="classic.js"></script>
// module/classic.js
import('./imported.js').then(()=>{
  console.log('imported.js is just imported from the module/classic.js');
});

这意味着,import()作为模块执行脚本实际上与在then()函数中我们可以使用模块导出(如module.default等)的语法一致。

const locale = 'en';
import(`./utils_${locale}.js`).then(
  (utils)=>{
    console.log('utils', utils);
    utils.default();
  }
);

关于调试 - 最突出的优点,你可以在浏览器DevTools控制台中访问ES模块,因为import()可以任何地方使用。
你可以轻松的加载、测试或者调试模块。让我们做一个简单的例子,加载一个官方ECMAScript版本的lodash(lodash-es)并检查其版本和一些其他功能:

import("https://cdn.rawgit.com/lodash/lodash/4.17.4-es/lodash.default.js")
.then(({default:_})=>{// load and use lodash 
 console.log(`lodash version ${_.VERSION} is loaded`)
 console.log('_.uniq([2, 1, 2]) :', _.uniq([2, 1, 2]));
});
Promise.all([
        import('./a.js'),
        import('./b.js'),
        import('./c.js'),
    ])
    .then(([a, {default: b}, {c}]) => {
        console.log('a.js is loaded dynamically');
        
        b('isDynamic');
        
        c('isDynamic');
    });
const CDNs = [
  {
    name: 'jQuery.com',
    url: 'https://code.jquery.com/jquery-3.1.1.min.js'
  },
  {
    name: 'googleapis.com',
    url: 'https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'
  }
];

console.log(`------`);
console.log(`jQuery is: ${window.jQuery}`);

Promise.race([
  import(CDNs[0].url).then(()=>console.log(CDNs[0].name, 'loaded')),
  import(CDNs[1].url).then(()=>console.log(CDNs[1].name, 'loaded'))
]).then(()=> {
  console.log(`jQuery version: ${window.jQuery.fn.jquery}`);
});
  • 作者:web修理工
  • 原文链接:https://blog.csdn.net/qq_42374676/article/details/120248302
    更新时间:2022-12-31 14:49:57