亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

背景

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

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

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

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

<!-- 動態(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),雖然要使用動態(tài)創(chuàng)建組件的父組件里已經(jīng)動態(tài)導(dǎo)入并注冊了子組件,但是始終無法顯示遍歷的Component 。

問題原因:

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

使用 app.component 全局注冊組件,循環(huán)遍歷創(chuàng)建多個 component的時候可以生效。
全局創(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中通過遍歷傳入組件名稱動態(tài)創(chuàng)建多個component 組件的文章就介紹到這了,更多相關(guān)vue3動態(tài)創(chuàng)建多個component 組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論