vue3中通過遍歷傳入組件名稱動態(tài)創(chuàng)建多個component 組件
背景
在 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)文章
vant使用datetime-picker組件設(shè)置maxDate和minDate的坑及解決
這篇文章主要介紹了vant使用datetime-picker組件設(shè)置maxDate和minDate的坑及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12
vue 列表頁跳轉(zhuǎn)詳情頁獲取id以及詳情頁通過id獲取數(shù)據(jù)
這篇文章主要介紹了vue 列表頁跳轉(zhuǎn)詳情頁獲取id以及詳情頁通過id獲取數(shù)據(jù),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03
Vue2.0 實現(xiàn)歌手列表滾動及右側(cè)快速入口功能
這篇文章主要介紹了Vue2.0實現(xiàn)歌手列表滾動及右側(cè)快速入口功能,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-08-08

