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

想把 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'
阅读 3.5k
1 个回答
const componentCreator = (key) => {
     return () => import(`../components/${key}.vue`)
}
const LocationList = componentCreator('LocationList')

这样试试

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题