vue異步組件與組件懶加載(解決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.csdn.net/zjcjava/article/details/82179975
https://blog.csdn.net/weixin_37221852/article/details/81297430

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章