Home >Web Front-end >Vue.js >How to dynamically create multiple component components in vue3 by traversing the incoming component names
In vue3, if you use component, you can dynamically load a component, for example
<!-- 直接创建 --> <component :is="Image" />
This will load the already defined and imported Image component, but if The custom components that need to be displayed are placed in an array. If the display is traversed, the display will not be successful.
<!-- 动态创建方式 1 --> <div v-for="(comp, index) in realTimeComponent" :key="index"> <component :is="comp" /> </div> <!-- 动态创建方式 2--> <component v-for="(comp, index) in realTimeComponent" :key="index" :is="comp" />
<script setup> import { ref } from "Vue"; import Image from "@/customComponents/Image.vue"; const realTimeComponent = ref(["Image"]); </script> 或者 <script> import { ref } from "Vue"; import Image from "@/customComponents/Image.vue"; export default { components: { Image, }, setup(){ const realTimeComponent = ref(["Image"]); } } </script>
The display effect is as shown in the figure:
After many attempts, we found that although we need to use the parent component of the dynamically created component The subcomponent has been dynamically imported and registered, but the traversed Component cannot be displayed.
During traversal, the component imported and registered in the current component cannot be recognized, and it will be considered that the component is not registered, thus displaying<image> image></image>
However, it can be recognized by directly using <component :is="Image"></component>
to register the component in this page.
Solution:
Use app.component to register the component globally, which can take effect when looping through to create multiple components.
Global creation method:
// src/customComponents/index.js import Button from "@/customComponents/Button.vue"; import Text from "@/customComponents/Text.vue"; import Icon from "@/customComponents/Icon.vue"; import Image from "@/customComponents/Image.vue"; const components = { install: function (app) { app.component("Button", Button).component("Text", Text).component("Icon", Icon).component("Image", Image); }, }; export default components; // main.js import components from "@/customComponents"; app.use(components);
The above is the detailed content of How to dynamically create multiple component components in vue3 by traversing the incoming component names. For more information, please follow other related articles on the PHP Chinese website!