vue3中如何動(dòng)態(tài)自定義創(chuàng)建組件并掛載

在日常開(kāi)發(fā)中,我們可能會(huì)遇到一種情況:組件太靈活,且無(wú)法預(yù)先定義。那么我們就需要能夠創(chuàng)建組件的能力,并且能組合到我們現(xiàn)有的界面中。

基礎(chǔ)API

// 創(chuàng)建
app.component(name, {})
// 組合
<component :is="createVueComponent()"></component>

很多人看到這里應(yīng)該就大致知道怎么做了,后面的示例可以直接略過(guò)~

示例

集成一個(gè)創(chuàng)建組件的方法

import { createApp } from 'vue';
import { TComponent } from './type';

export const createVueComponent = (component: TComponent) => {
    const app = createApp({});
    app.component(component.name, {
        template: component.template,
        data: () => component.data || {},
        props: component.props || {},
        methods: component.methods,
        onMounted: component.onMounted,
    });
    return app.component(component.name);
};

使用場(chǎng)景

這里正在向低代碼擴(kuò)展,所以只能存儲(chǔ)字符串,那么這里就得有能利用字符串創(chuàng)建組的能力。

 <!-- 自定義內(nèi)容 -->
 <template v-else-if="item.slot">
   <!-- 低代碼:利用字符串創(chuàng)建新的組件 -->
   <component v-if="(typeof item.slot === 'object')" 
     :is="createVueComponent({ name: item?.slot?.name || '', template: item.slot.template, props: item.slot.props  })" 
     :row="scope.row" :index="scope.$index" :label="item.label" ></component>
   <!-- 當(dāng)組件使用 -->
   <slot v-else :name="'zh-table-' + item.prop" :row="scope.row" :index="scope.$index" :label="item.label" />
 </template>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容