vue3+ts 动态导入多文件组件

 1、在components文件夹中新建index.ts文件(components文件夹下为创建的组件)

// index.ts
const modules = import.meta.globEager("./*.vue");  //参数为组件路径
let componentsOpts = {}

const getCaption = (obj, str, z: boolean) => {
  let index = obj.lastIndexOf(str);
  if (z) index += str.length
  // z为true则截取/之后的内容,反之
  obj = z ? obj.substring(index, obj.length) : obj.substring(0, index);
  return obj;
};

for (let path in modules) {
  let str = getCaption(path, './', true)
  str = getCaption(str, '.vue', false)
  componentsOpts[str] = modules[path]['default']
}

export default componentsOpts

2、在vue文件中引入组件

// list.vue




你可能感兴趣的:(vue,javascript,前端,ts,vue3,组件)