本文共 3636 字,大约阅读时间需要 12 分钟。
通常我们比较常用的vue组件加载方式就是通过import引入文件,如:路由懒加载 、静态的import。
一般情况下还是推荐使用import方式引入的,因为这更容易从Tree_shaking 及一些分析工具中受益。
在一些比较特殊的场景,比如:
假如后台返回了以下JSON数据结构
[ { "alwaysShow":true, "children":[ { "alwaysShow":false, "component":"OA/AskForLeaveManagement/AskForLeaveManagement", "hidden":false, "meta":{ "icon":"", "id":2004, "title":"请假管理" }, "name":"AskForLeaveManagement", "path":"askForLeaveManagement", "redirect":"" }, { "alwaysShow":false, "children":[ ], "component":"OA/WorkOvertimeManagement/WorkOvertimeManagement", "hidden":false, "meta":{ "icon":"", "id":3687, "title":"加班管理" }, "name":"WorkOvertimeManagement", "path":"workOvertimeManagement", "redirect":"" }, ], "component":"Layout", "hidden":false, "meta":{ "icon":"dashboard", "id":2001, "title":"办公管理" }, "name":"Oa", "path":"/oa", "redirect":"noRedirect" }, { "alwaysShow":false, "children":[ ], "component":"Layout", "hidden":true, "meta":{ "icon":"", "id":3618, "title":"首页" }, "name":"Dashboard", "path":"/dashboard", "redirect":"" }]
一般vue路由会类似这样定义
{ path: '/redirect', component: Layout, hidden: true, children: [ { path: '/redirect/:path*', component: () => import('@/views/redirect/index'), }, ], }, { path: '/login', component: () => import('@/views/login/index'), hidden: true, }, { path: '/auth-redirect', component: () => import('@/views/login/auth-redirect'), hidden: true, },
从JSON数据结构转换到vue路由定义,我们只需要进行递归处理就好 。
但这里面我们需要重点关注 component的实现
component:()=>import('@/views/redirect/index'),
假如我们继续通过import 引入组件的方式,在我们进行递归处理进行动态赋值时,比如
component:()=>import('@/views/' + path ),
会发现 import 其实是不支持动态变量的,所以我们通过这种方式是无法正确找到路由的
针对上面使用 import 出现无法正确找到路由的情况,我们可以通过这种方式处理。
定义loadComponent函数,将后台返回内容处理后, 再赋值给 component
const loadComponent = (path) => { // 路由懒加载 return (resolve) => require(['../../components' + path], resolve)}
假如想加载不同文件夹下的vue文件, 我们需要声明文件目录的前缀, 不然也会报错的
export const loadViews = (view) => { // 路由懒加载 return (resolve) => require(['../../views/' + view], resolve)}export const loadComponents = (path) => { // 路由懒加载 return (resolve) => require(['../../components' + path], resolve)}
通过这种方式改造后,Vue路由可以完全的通过后台进行控制, 如: 公用组件的参数设置、动态设置按钮关联组件等等
假如想通过某个按钮点击后加载某个vue组件, 可以封装上面的方法, 大致如下
getComponents(value) { return new Promise((r, j) => { const url = value.replace('', '/') if (url.includes('components')) { const path = url.replace('components', '') require(['@/components' + path], function(v) { r(v) }).catch(e => { console.log('error', e) j(new Error(`无法找到组件,请确认地址是否正确`)) }) } else { require(['@/views/' + url], function(v) { r(v) }).catch(e => { console.log('error', e) j(new Error(`无法找到组件,请确认地址是否正确`)) }) } }) },
有哪里写的不好或者想讨论的可以在下方 评论区跟我讨论噢
转载地址:http://ktfkp.baihongyu.com/