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āng)前組件中導(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)文章
ant-design-vue 實現(xiàn)表格內(nèi)部字段驗證功能
這篇文章主要介紹了ant-design-vue 實現(xiàn)表格內(nèi)部字段驗證功能,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-12-12
Vue3+Element?Plus實現(xiàn)動態(tài)標(biāo)簽頁以及右鍵菜單功能
這篇文章主要給大家介紹了關(guān)于Vue3+Element?Plus實現(xiàn)動態(tài)標(biāo)簽頁以及右鍵菜單功能的相關(guān)資料,Vue?3和Element?Plus提供了一種簡單的方法來實現(xiàn)側(cè)邊菜單欄與標(biāo)簽頁之間的聯(lián)動,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2023-09-09
element?ui中el-form-item的屬性rules的用法示例小結(jié)
這篇文章主要介紹了element?ui中el-form-item的屬性rules的用法,本文通過實例代碼給大家介紹的非常詳細,感興趣的朋友一起看看吧2024-07-07
Vue結(jié)合ElementUI實現(xiàn)數(shù)據(jù)請求和頁面跳轉(zhuǎn)功能(最新推薦)
我們在Proflie.vue實例中,有beforeRouteEnter、beforeRouteLeave兩個函數(shù)分別是進入路由之前和離開路由之后,我們可以在這兩個函數(shù)之內(nèi)進行數(shù)據(jù)的請求,下面給大家分享Vue結(jié)合ElementUI實現(xiàn)數(shù)據(jù)請求和頁面跳轉(zhuǎn)功能,感興趣的朋友一起看看吧2024-05-05
vue使用ElementUI時導(dǎo)航欄默認展開功能的實現(xiàn)
這篇文章主要介紹了vue使用ElementUI時導(dǎo)航欄默認展開功能的實現(xiàn),本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2018-07-07

