把Vue3模板復(fù)用玩到了極致,少封裝幾十個(gè)組件!
普通的場(chǎng)景
最近在做 Vue3 項(xiàng)目的時(shí)候,在思考一個(gè)小問(wèn)題,其實(shí)是每個(gè)人都做過(guò)的一個(gè)場(chǎng)景,很簡(jiǎn)單,看下方代碼:
其實(shí)就是一個(gè)普通的不能再普通的循環(huán)遍歷渲染的案例,咱們往下接著看,如果這樣的遍歷在同一個(gè)組件里出現(xiàn)了很多次,比如下方代碼:
這個(gè)時(shí)候我們應(yīng)該咋辦呢?誒!很多人很快就能想出來(lái)了,那就是把循環(huán)的項(xiàng)抽取出來(lái)成一個(gè)組件,這樣就能減少很多代碼量了,比如我抽取成 Item.vue 這個(gè)組件:
然后直接可以引用并使用它,這樣大大減少了代碼量,并且統(tǒng)一管理,提高代碼可維護(hù)性!!!
不難受嗎?
但是我事后越想越難受,就一個(gè)這么丁點(diǎn)代碼量的我都得抽取成組件,那我不敢想象以后我的項(xiàng)目組件數(shù)會(huì)多到什么地步,而且組件粒度太細(xì),確實(shí)也增加了后面開(kāi)發(fā)者的負(fù)擔(dān)~
那么有沒(méi)有辦法,可以不抽取成組件呢?我可以在當(dāng)前組件里去提取嗎,而不需要去重新定義一個(gè)組件呢?例如下面的效果:
useTemplate 代碼實(shí)現(xiàn)
想到這,馬上行動(dòng)起來(lái),需要封裝一個(gè) useTemplate來(lái)實(shí)現(xiàn)這個(gè)功能:
用的不爽
盡管做到這個(gè)地步,我還是覺(jué)得用的不爽,因?yàn)闆](méi)有類(lèi)型提示:
我們想要的是比較爽的使用,那肯定得把類(lèi)型的提示給支持上啊!!!于是給 useTemplate 加上泛型!!加上之后就有類(lèi)型提示啦~~~~
加上泛型后的 useTemplate 代碼如下:
完整代碼
import { defineComponent, shallowRef } from 'vue';
import { camelCase } from 'lodash';
import type { DefineComponent, Slot } from 'vue';
// 將橫線命名轉(zhuǎn)大小駝峰
function keysToCamelKebabCase(obj: Record<string, any>) {
const newObj: typeof obj = {};
for (const key in obj) newObj[camelCase(key)] = obj[key];
return newObj;
}
export type DefineTemplateComponent<
Bindings extends object,
Slots extends Record<string, Slot | undefined>,
> = DefineComponent<object> & {
new (): { $slots: { default(_: Bindings & { $slots: Slots }): any } };
};
export type ReuseTemplateComponent<
Bindings extends object,
Slots extends Record<string, Slot | undefined>,
> = DefineComponent<Bindings> & {
new (): { $slots: Slots };
};
export type ReusableTemplatePair<
Bindings extends object,
Slots extends Record<string, Slot | undefined>,
> = [DefineTemplateComponent<Bindings, Slots>, ReuseTemplateComponent<Bindings, Slots>];
export const useTemplate = <
Bindings extends object,
Slots extends Record<string, Slot | undefined> = Record<string, Slot | undefined>,
>(): ReusableTemplatePair<Bindings, Slots> => {
const render = shallowRef<Slot | undefined>();
const define = defineComponent({
setup(_, { slots }) {
return () => {
// 將復(fù)用模板的渲染函數(shù)內(nèi)容保存起來(lái)
render.value = slots.default;
};
},
}) as DefineTemplateComponent<Bindings, Slots>;
const reuse = defineComponent({
setup(_, { attrs, slots }) {
return () => {
// 還沒(méi)定義復(fù)用模板,則拋出錯(cuò)誤
if (!render.value) {
throw new Error('你還沒(méi)定義復(fù)用模板呢!');
}
// 執(zhí)行渲染函數(shù),傳入 attrs、slots
const vnode = render.value({ ...keysToCamelKebabCase(attrs), $slots: slots });
return vnode.length === 1 ? vnode[0] : vnode;
};
},
}) as ReuseTemplateComponent<Bindings, Slots>;
return [define, reuse];
};