本文小編為大家詳細介紹“vue3中如何通過遍歷傳入組件名稱動態創建多個component組件”,內容詳細,步驟清晰,細節處理妥當,希望這篇“vue3中如何通過遍歷傳入組件名稱動態創建多個component組件”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學習新知識吧。
創新互聯建站是一家朝氣蓬勃的網站建設公司。公司專注于為企業提供信息化建設解決方案。從事網站開發,網站制作,網站設計,網站模板,微信公眾號開發,軟件開發,小程序設計,10年建站對搬家公司等多個行業,擁有多年的營銷推廣經驗。
在 vue3 中,如果使用 component,可以動態加載一個組件,例如
<!-- 直接創建 --> <component :is="Image" />
這樣會將已經定義好并導入的比如 Image 組件加載出來,但是如果將需要展示的自定義組件放在一個數組中,遍歷展示,則無法展示成功。
<!-- 動態創建方式 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>
展示效果如圖:
經過多次嘗試發現,雖然要使用動態創建組件的父組件里已經動態導入并注冊了子組件,但是始終無法顯示遍歷的Component 。
在遍歷的時候,當前組件中導入并注冊該組件無法識別,會認為沒有注冊該組件,從而展示<image></image>
但是,單獨直接使用<component :is="Image" />
該頁面中注冊該組件,是可以被識別的。
解決方案:
使用 app.component 全局注冊組件,循環遍歷創建多個 component的時候可以生效。
全局創建方法:
// 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);
讀到這里,這篇“vue3中如何通過遍歷傳入組件名稱動態創建多個component組件”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注創新互聯行業資訊頻道。
文章標題:vue3中如何通過遍歷傳入組件名稱動態創建多個component組件
網頁URL:http://m.kartarina.com/article4/jedgoe.html
成都網站建設公司_創新互聯,為您提供網站改版、Google、微信公眾號、定制開發、、用戶體驗
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯