vue3+vite 批量引入组件动态使用

  • Post author:
  • Post category:vue




引入组件

const modules = import.meta.glob('./components-new/*.vue');
const components: any = ref({});
Object.entries(modules).forEach(([path, asyncCom]) => {
  const name = path.replace(/\.\/components-new\/(.*)\.vue/, '$1');
  components.value[name] = markRaw(defineAsyncComponent(asyncCom));
});



动态使用组件

<div v-for="(item, index) in componentList" :key="index" class="wow">
      <template v-if="item.show">
        <component :is="components[item.name]"></component>
      </template>
    </div>



控制组件显隐与顺序


const componentList: any = ref([
  { name: 'comp1', show: false },
  { name: 'comp2', show: false },
  { name: 'comp3', show: false },
  { name: 'comp4', show: false },
  { name: 'comp5', show: false },
  { name: 'comp6', show: false },
  { name: 'comp7', show: false },
]);



版权声明:本文为qq_44900902原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。