在日常開(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>