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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Alecor/article/details/83056952

在写项目的时候,需要动态配置路由菜单,所有的菜单都是通过配置生成的,这就意味着菜单的路径(在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.csdn.net/zjcjava/article/details/82179975
https://blog.csdn.net/weixin_37221852/article/details/81297430

猜你喜欢

转载自blog.csdn.net/Alecor/article/details/83056952
今日推荐