欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue3中通過遍歷傳入組件名稱動(dòng)態(tài)創(chuàng)建多個(gè)component 組件

 更新時(shí)間:2023年03月23日 14:20:03   作者:蓓蕾心晴  
這篇文章主要介紹了vue3中通過遍歷傳入組件名稱動(dòng)態(tài)創(chuàng)建多個(gè)component 組件,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

背景

在 vue3 中,如果使用 component,可以動(dòng)態(tài)加載一個(gè)組件,例如

<!--   直接創(chuàng)建  -->
<component :is="Image" />

這樣會(huì)將已經(jīng)定義好并導(dǎo)入的比如 Image 組件加載出來,但是如果將需要展示的自定義組件放在一個(gè)數(shù)組中,遍歷展示,則無法展示成功。

<!-- 動(dòng)態(tài)創(chuàng)建方式 1 -->
<div v-for="(comp, index) in realTimeComponent" :key="index">
    <component :is="comp" />
</div>

<!-- 動(dòng)態(tài)創(chuàng)建方式 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>

展示效果如圖:

解決

經(jīng)過多次嘗試發(fā)現(xiàn),雖然要使用動(dòng)態(tài)創(chuàng)建組件的父組件里已經(jīng)動(dòng)態(tài)導(dǎo)入并注冊(cè)了子組件,但是始終無法顯示遍歷的Component 。

問題原因:

在遍歷的時(shí)候,當(dāng)前組件中導(dǎo)入并注冊(cè)該組件無法識(shí)別,會(huì)認(rèn)為沒有注冊(cè)該組件,從而展示<image></image>
但是,單獨(dú)直接使用<component :is="Image" />該頁面中注冊(cè)該組件,是可以被識(shí)別的。
解決方案:

使用 app.component 全局注冊(cè)組件,循環(huán)遍歷創(chuàng)建多個(gè) component的時(shí)候可以生效。
全局創(chuàng)建方法:

// 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);

問題解決!

到此這篇關(guān)于vue3中通過遍歷傳入組件名稱動(dòng)態(tài)創(chuàng)建多個(gè)component 組件的文章就介紹到這了,更多相關(guān)vue3動(dòng)態(tài)創(chuàng)建多個(gè)component 組件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論