vue 如何根据列表动态生成组件?

目录结构如下
image.png

--config
    --v-input
        index.vue
    --v-select
        index.vue
    --v-number
        index.vue
    register.js
--utils
    create.js
  • example
// 在register.js 给你一个这样的列表
const COMPONENT_LIST = ['v-input','v-select','v-number']
// 在 utils/create.js 封装一个 create 函数生成这样的结构
{
    'v-input':()=>import('xxx/v-input/index.vue'),
    'v-select':()=>import('xxx/v-select/index.vue'),
    'v-number':()=>import('xxx/v-number/index.vue'),
}

自己尝试封装了一个函数

export const createAsyncComponentByPath = path => () => {
  try {
    return Promise.resolve(require(`${path}`).default)
  } catch (e) {
    console.error(e)
  }
}

const createComponentsByList = list => {
  return list.reduce((res, name) => {
    res[name] = createAsyncComponentByPath(`./${name}/index.vue`)
    return res
  }, {})
}

export const COMPONENTS = createComponentsByList(COMPONENT_LIST)

但是只支持写自身的相对路径,一旦独立封装到 create.js,就可能会出现路径报错.

求大佬出个完美的解决方案~!

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