vue 异步组件 components 如何用函数引入

mikechen
  • 711

想把 components 独立出来,写成这样一份 js

  • components.js

    const COMPONENTS = {
    LocationList: () => import('../components/LocationList'),
    StationList: () => import('../components/StationList'),
    DeviceSelectList: () => import('../components/DeviceSelectList'),
    }
    export default COMPONENTS
  • index.vue

    import COMPONENTS from './components.js'
    export default {
    components: COMPONENTS
    }

    这样是可以用的

但是我改成函数的形式就报错了

// 所有的组件

+    const componentCreator = (path) => {
+      return () => import(path)
+    }
+    const LocationList = componentCreator('../components/LocationList')
+    console.log('LocationList', LocationList)

const COMPONENTS = {
- LocationList: () => import('../components/LocationList'),
+ LocationList,
  StationList: () => import('../components/StationList'),
  DeviceSelectList: () => import('../components/DeviceSelectList'),
}

export default COMPONENTS

这样就渲染不出来对应的组件
vue 发出警告

vue.runtime.esm.js?2b0e:619 [Vue warn]: Failed to resolve async component: function () {
    return Promise.resolve("".concat(path)).then(function (s) {
      return Object(_Users_ishowYoung_Project_shuyi_front_end_node_modules_babel_runtime_helpers_esm_interopRequireWildcard__WEBPACK_IMPORTED_MODULE_1__["default"])(__webpack_require__("./src/components/common-email/src sync recursive")(s));
    });
  }
Reason: Error: Cannot find module '../components/LocationList'
回复
阅读 624
1 个回答
const componentCreator = (key) => {
     return () => import(`../components/${key}.vue`)
}
const LocationList = componentCreator('LocationList')

这样试试

感觉是一个范围巨大的path变量让webpack使用require.context没有预判你的导入范围

宣传栏