把Vue3模板復(fù)用玩到了極致,少封裝幾十個組件!
普通的場景
最近在做 Vue3 項目的時候,在思考一個小問題,其實是每個人都做過的一個場景,很簡單,看下方代碼:
其實就是一個普通的不能再普通的循環(huán)遍歷渲染的案例,咱們往下接著看,如果這樣的遍歷在同一個組件里出現(xiàn)了很多次,比如下方代碼:
這個時候我們應(yīng)該咋辦呢?誒!很多人很快就能想出來了,那就是把循環(huán)的項抽取出來成一個組件,這樣就能減少很多代碼量了,比如我抽取成 Item.vue 這個組件:
然后直接可以引用并使用它,這樣大大減少了代碼量,并且統(tǒng)一管理,提高代碼可維護性!??!
不難受嗎?
但是我事后越想越難受,就一個這么丁點代碼量的我都得抽取成組件,那我不敢想象以后我的項目組件數(shù)會多到什么地步,而且組件粒度太細,確實也增加了后面開發(fā)者的負擔(dān)~
那么有沒有辦法,可以不抽取成組件呢?我可以在當(dāng)前組件里去提取嗎,而不需要去重新定義一個組件呢?例如下面的效果:
useTemplate 代碼實現(xiàn)
想到這,馬上行動起來,需要封裝一個 useTemplate來實現(xiàn)這個功能:
用的不爽
盡管做到這個地步,我還是覺得用的不爽,因為沒有類型提示:
我們想要的是比較爽的使用,那肯定得把類型的提示給支持上?。。。∮谑墙o useTemplate 加上泛型?。〖由现缶陀蓄愋吞崾纠瞺~~~
加上泛型后的 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)容保存起來
render.value = slots.default;
};
},
}) as DefineTemplateComponent<Bindings, Slots>;
const reuse = defineComponent({
setup(_, { attrs, slots }) {
return () => {
// 還沒定義復(fù)用模板,則拋出錯誤
if (!render.value) {
throw new Error('你還沒定義復(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];
};