最近在做 Vue3 項目的時候,在思考一個小問題,其實是每個人都做過的一個場景,很簡單,看下方代碼:
其實就是一個普通的不能再普通的循環遍歷渲染的案例,咱們往下接著看,如果這樣的遍歷在同一個組件里出現了很多次,比如下方代碼:
這個時候我們應該咋辦呢?誒!很多人很快就能想出來了,那就是把循環的項抽取出來成一個組件,這樣就能減少很多代碼量了,比如我抽取成 Item.vue 這個組件:
然后直接可以引用并使用它,這樣大大減少了代碼量,并且統一管理,提高代碼可維護性!!!
但是我事后越想越難受,就一個這么丁點代碼量的我都得抽取成組件,那我不敢想象以后我的項目組件數會多到什么地步,而且組件粒度太細,確實也增加了后面開發者的負擔~
那么有沒有辦法,可以不抽取成組件呢?我可以在當前組件里去提取嗎,而不需要去重新定義一個組件呢?例如下面的效果:
想到這,馬上行動起來,需要封裝一個 useTemplate來實現這個功能:
盡管做到這個地步,我還是覺得用的不爽,因為沒有類型提示:
我們想要的是比較爽的使用,那肯定得把類型的提示給支持上啊!!!于是給 useTemplate 加上泛型!!加上之后就有類型提示啦~~~~
加上泛型后的 useTemplate 代碼如下:
import { defineComponent, shallowRef } from 'vue';import { camelCase } from 'lodash';import type { DefineComponent, Slot } from 'vue';// 將橫線命名轉大小駝峰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 () => { // 將復用模板的渲染函數內容保存起來 render.value = slots.default; }; }, }) as DefineTemplateComponent<Bindings, Slots>; const reuse = defineComponent({ setup(_, { attrs, slots }) { return () => { // 還沒定義復用模板,則拋出錯誤 if (!render.value) { throw new Error('你還沒定義復用模板呢!'); } // 執行渲染函數,傳入 attrs、slots const vnode = render.value({ ...keysToCamelKebabCase(attrs), $slots: slots }); return vnode.length === 1 ? vnode[0] : vnode; }; }, }) as ReuseTemplateComponent<Bindings, Slots>; return [define, reuse];};
本文鏈接:http://www.www897cc.com/showinfo-26-65873-0.html把Vue3模板復用玩到了極致,少封裝幾十個組件!
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: Prettier + ESLint + Rust = ?? 快,真是太快了!
下一篇: C++泛型編程:解鎖代碼靈活性的奧秘