目录结构

批量引入组件

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

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

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

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

 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. 

原文地址:https://blog.csdn.net/weixin_43743175/article/details/134715903

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_14407.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注