vue3+vite 批量引入局部组件及使用

目录结构

批量引入组件

例如:src/views/oss/components/customComponents.ts

import { ref, defineAsyncComponent, markRaw } from 'vue';

const modules = import.meta.glob('./*.vue');

//这告诉 TypeScript,components.value 是一个键为字符串、值为 defineAsyncComponent 返回类型的对象。
const components = ref<Record<string, ReturnType<typeof defineAsyncComponent>>>({});

 Object.entries(modules).forEach(([path, asyncCom]) => {
  const name = path.replace(/\.\/(.*)\.vue/, '$1');
  components.value[name] = markRaw(defineAsyncComponent(asyncCom));
});

export default components

 动态使用组件

<template>
   <div v-for="(item, index) in componentList" :key="index">
      <component :is="customComponents[item]"></component>
   </div>
</template>

<script setup name="Oss" lang="ts">
   import customComponents from "./components/customComponents"

   const componentList: any = ref(['comp1' ,'comp-test' ,'Comp2' ,'CompTest2']);
</script>

或者单个使用

<template>
  <component :is="customComponents['comp1']"></component>
  <component :is="customComponents['Comp2']"></component>
  <component :is="customComponents['comp-test']"></component>
  <component :is="customComponents['CompTest2']"></component>
</template>

<script setup name="Oss" lang="ts">
   import customComponents from "./components/customComponents"
</script>

错误使用

注意:封装的批量方法仅仅只作用于批量引入组件,并未将其注册为全局组件,所以不能将其直接以组件形式使用

<template>
   <comp1 />
   <Comp2 />
   <comp-test />
   <CompTest2 />
</template>

控制台会报出以下警告

index.vue:370  [Vue warn]: Failed to resolve component: comp1
If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement. 

猜你喜欢

转载自blog.csdn.net/weixin_43743175/article/details/134715903
今日推荐