v3+ts 批量引入组件

发布于:2025-02-11 ⋅ 阅读:(36) ⋅ 点赞:(0)

代码

html

  <component :is="data.componentsshow[data.showc]" 
:msg="'动态组件传值可以这样吗?'" :msgtwo="'动态组件传值可以这样!'" 
@senddata="senddata"></component>

data.componentsshow[data.showc]  等于  data.componentsshow.oneChapter

js

const data = reactive({
  componentsshow: {},
  showc: ''
})





//所有组件信息
//studentChapter 文件夹下的所有组件
//截取方法
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;
};
//循环打印组件
//截取之前
// ./studentChapter/oneChapter.vue 组件----
//截取之后
//  oneChapter.vue
const getComponentsList = () => {
  const select_modules = import.meta.glob("../components/studentChapter/*.vue");
  for (const key in select_modules) {
    let starter = getCaption(key, "./studentChapter/", true);
    let name = getCaption(starter, ".vue", false);
    select_modules[key]().then(res => {
      data.componentsshow[name] = shallowRef(res.default);
    });
  }
}


const sendChapter = (e) => {
  //我要使用那个组件 
  //组件名称就是,组件的文件名字
  console.log(e, '组件名称');
  getComponentsList()
  data.showc = e;
}

关于动态组件传值和原本v3传值是一样的。


网站公告

今日签到

点亮在社区的每一天
去签到