vue异步组件与组件懒加载(解决import不能导入变量字符串的路径问题)

本文探讨了在Vue项目中实现动态路由菜单的配置方法,特别是在使用webpack时如何正确处理异步加载的问题。文章分析了错误的import用法,并提供了两种解决方案:利用字符串模板和自定义懒加载函数,以实现组件的按需加载。

在写项目的时候,需要动态配置路由菜单,所有的菜单都是通过配置生成的,这就意味着菜单的路径(在vue开发项目里面就是一个字符串的路径)需要异步加载进去,但是由于对webpack的import不是很熟悉,所以就有一下的坑需要填了

错误的原因分析

_import.js
module.exports = file => () => import(file)

在这里插入图片描述

但是这种方法错误的原因是:

webpack 编译es6 动态引入 import() 时不能传入变量,例如dir =’path/to/my/file.js’ ; import(dir) , 而要传入字符串 import(‘path/to/my/file.js’),这是因为webpack的现在的实现方式不能实现完全动态。

解决方案一:

可以通过字符串模板来提供部分信息给webpack;例如import(./path/${myFile}), 这样编译时会编译所有./path下的模块,但运行时确定myFile的值才会加载,从而实现懒加载。

在这里插入图片描述

解决方案二:

function lazyLoadView(AsyncView) {
  const AsyncHandler = () => ({
    component: AsyncView,
      // A component to use while the component is loading.
    loading: require('@/view/system/Loading.vue').default,
      // A fallback component in case the timeout is exceeded
      // when loading the component.
    error: require('@/view/system/Timeout.vue').default,
      // Delay before showing the loading component.
      // Default: 200 (milliseconds).
    delay: 200,
      // Time before giving up trying to load the component.
      // Default: Infinity (milliseconds).
    timeout: 10000
  });
  return Promise.resolve({
    functional: true,
    render(h, { data, children }) {
        // Transparently pass any props or children
        // to the view component.
      return h(AsyncHandler, data, children);
    }
  });
}
const My = () => lazyLoadView(import('@/view/My.vue'));
const router = new VueRouter({
  routes: [
    {
      path: '/my',
      component: My
    }
  ]
})

通过上述两种方法都能够解决 动态组件的懒加载效果

感谢
https://blog.youkuaiyun.com/zjcjava/article/details/82179975
https://blog.youkuaiyun.com/weixin_37221852/article/details/81297430

评论 11
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值