vue?封裝一個高質(zhì)量的表單通用組件
正文
我們都知道表單組件應(yīng)該是后臺管理系統(tǒng)中用得最多的組件,我們不可能每個業(yè)務(wù)都寫一次表單,然后每一次修改都去各自業(yè)務(wù)中大幅修改,這樣就可能導(dǎo)致代碼重復(fù)率太高了,工作效率頻頻降低,所以我們需要封裝起來,這樣我們就可以復(fù)用,大大減少項目體積,方便項目的后期維護(hù),提高前端娃的工作效率。由于我們使用表單都是直接使用UI組件庫的組件,所以我們需要做二次封裝,那么問題來了,二次封裝表單組件我們需要考慮什么?
基于Element-plus實現(xiàn)二次封裝表單組件
- 特性復(fù)用:必須繼承原有組件的所有特性。
- 命名規(guī)范:二次組件名必須見名知意,我們一般都是起一個公用名+原有組件名,比如lib-form。
- 接口簡單:自定義暴露出來的接口越簡單越好。
- 容易拓展:留有自定義插槽,讓用戶可以自己選擇。
- 功能完善:具備更完善的功能如:表單驗證、動態(tài)刪減表單,集成第三方的插件(富文本)...
- 場景通用:具備多個場景使用,比如彈框嵌套表單、頁面嵌套表單。
封裝一個高質(zhì)量的通用組件,上面是真的只是基操,話不多說,直接上實踐手把手教你封裝組件。
步驟1
繼承原有組件的所有特性(這也是封裝的核心)。先明確三個大方向:
表單固定屬性,繼承Form表單的所有屬性、方法。
// 定義el-form的ref繼承原有組件的form屬性 export interface FormInstance { registerLabelWidth(width: number, oldWidth: number): void, deregisterLabelWidth(width: number): void, autoLabelWidth: string | undefined, emit: (evt: string, ...args: any[]) => void, labelSuffix: string, inline?: boolean, model?: Record<string, unknown>, size?: string, showMessage?: boolean, labelPosition?: string, labelWidth?: string, rules?: Record<string, unknown>, statusIcon?: boolean, hideRequiredAsterisk?: boolean, disabled?: boolean, validate: (callback?: Callback) => Promise<boolean>, resetFields: () => void, clearValidate: (props?: string | string[]) => void, validateField: (props: string | string[], cb: ValidateFieldCallback) => void, }
表單項固定屬性,繼承表單項的所有屬性、方法。
// 表單每一項的配置選項 export interface FormOptions { // 表單項顯示的元素 type: '',// 定義表單項類型 value?: any, // 表單項的值 label?: string,// 表單項label prop?: string,// 表單項的標(biāo)識 rules?: RuleItem[],// 表單項的驗證規(guī)則 placeholder?: string,// 表單項的占位符 attrs?: { // 按需定義不同表單類型屬性 ... }, children?: FormOptions[],// 表單項的子元素,可能存在嵌套表單組件,如select ....// 適當(dāng)擴(kuò)展我們需要的屬性,比如上傳組件屬性,行布局表單屬性 }
由于Element-plus組件都是以el-為前綴,所以type取值只需要取el-后面部分作為值就行,比如el-input取 'input' 為值。
表單驗證效果,繼承組件原有的所有驗證屬性。由于Element-plus的驗證都是使用 async-validator 這個插件的驗證方法,直接復(fù)用插件源碼路徑async-validator/src/interface.ts文件下的所有代碼:
// 核心代碼:封裝驗證方式時的屬性 export interface RuleItem { type?: RuleType; // 驗證種類 required?: boolean;// 是否必填 pattern?: RegExp | string;// 驗證方式匹配 min?: number; // 表單項最小值 max?: number; // 表單項最大值 len?: number; // 表單項字符長度 trigger?: string | string[];// 驗證觸發(fā)方式 .... }
步驟2
實現(xiàn)一個完善的通用組件封裝,通過對標(biāo)簽封裝、接口 暴露、開發(fā)者傳參等。明確表單類型,根據(jù)不同類型表單復(fù)用多種場景,不僅開發(fā)者用戶拓展,而且,讓開發(fā)者用最少代碼就可以復(fù)用:
<!--表單框架:model就是傳入的表單對象,rules就是傳入的驗證對象 --> <el-form v-if="model" :validate-on-rule-change="false" v-bind="$attrs" :model="model" :rules="rules" ref="form" > ... <!--表單項封裝 --> </el-form>
普通表單項封裝,比如日期、輸入等組件。
<template v-for="(item, index) in options" :key="index"> <el-form-item :label="item.label" :prop="item.prop"> <component v-else :is="`el-${item.type}`" v-bind="item.attrs" v-model="model[item?.prop!]" > </component> </el-form-item> </template>
嵌套表單項封裝,比如下拉框,除了select組件還嵌套o(hù)ption組件。
<template v-for="(item, index) in options" :key="index"> <el-form-item v-if="item.children && item.children.length" :label="item.label" :prop="item.prop" > <component :is="`el-${item.type}`" v-bind="item.attrs" v-model="model[item?.prop!]" > <component v-for="(child, i) in item.children" :key="i" :label="child.label" :value="child.value" :is="`el-${child.type}`" > </component> </component> </el-form-item> </template>
富文本表單項封裝
本文使用的是wangEditor。
<div id="editor" v-else-if="item.type === 'editor'"></div>
import E from 'wangeditor'; // 遍歷傳入的prop的options對象,初始化富文本 if (item.type === 'editor') { // 初始化富文本 nextTick(() => { if (document.getElementById('editor')) { const editor = new E('#editor'); editor.config.placeholder = item.placeholder!; editor.create(); // 初始化富文本的內(nèi)容 editor.txt.html(item.value); editor.config.onchange = (newHtml: string) => { model.value[item.prop!] = newHtml; }; edit.value = editor; } }); }
上傳表單項封裝
向開發(fā)者暴露上傳的核心方法:預(yù)覽、刪除、上傳成功等,同時允許開發(fā)者自定義上傳信息以及渲染區(qū)域等。
<el-form-item :label="item.label" :prop="item.prop"> <!-- 上傳表單 --> <el-upload v-if="item.type === 'upload'" v-bind="item.uploadAttrs" :on-preview="onPreview" :on-remove="onRemove" :on-success="onSuccess" :on-error="onError" :on-progress="onProgress" :on-change="onChange" :before-upload="beforeUpload" :before-remove="beforeRemove" :http-request="httpRequest" > <slot name="uploadArea"></slot> <slot name="uploadTip"></slot> </el-upload> </el-form-item>
同行多個表單布局封裝
有時業(yè)務(wù)需要,一行可以定義多個表單,所以需要使用el-row,此時需要修改FormOptions屬性接口,完善多個表單場景,cols是一個數(shù)組定義FormOptions數(shù)組,colOption是el-col組件的相關(guān)屬性,然后重新復(fù)用嵌套表單的代碼。
<template v-if="item.type === 'row'"> <el-row :gutter="item.rowGutter"> <el-col v-for="(jtem, jndex) in item.cols" v-bind="jtem.colOption" :key="jndex" > <el-form-item :label="jtem.label" :prop="jtem.prop"> <component :is="`el-${jtem.type}`" v-bind="jtem.attrs" v-model="model[jtem?.prop!]" > <template v-if="jtem.children && jtem.children.length"> <component v-for="(child, i) in jtem.children" :key="i" :label="child.label" :value="child.value" :is="`el-${child.type}`" > </component> </template> </component> </el-form-item> </el-col> </el-row> </template>
- 自定義插槽:開發(fā)者可以根據(jù)需要,在封裝的el-form中添加插槽,可以允許組件功能的拓展,我們可以根據(jù)自己需要進(jìn)行封裝,這里就不一一演示了。
提交取消按鈕區(qū)域:這個最好可以實現(xiàn)插槽讓開發(fā)者可以自定義。
<el-form-item> <slot name="action" :form="form" :model="model"></slot> </el-form-item>
步驟3
開發(fā)者的調(diào)用封裝組件,通過配置不同表單類型的數(shù)組,然后調(diào)用lib-form封裝組件實現(xiàn)業(yè)務(wù)代碼復(fù)用。
組件的調(diào)用:根據(jù)業(yè)務(wù)需要,可以適當(dāng)定義我們需要的組件屬性以及必須要傳的參數(shù)。
<lib-form ref="form" label-width="100px" :options="options" @on-change="handleChange" @before-upload="handleBeforeUpload" @on-preview="handlePreview" @on-remove="handleRemove" @before-remove="beforeRemove" @on-success="handleSuccess" @on-exceed="handleExceed" > <template #uploadArea> <el-button size="small" type="primary">Click to upload</el-button> </template> <template #uploadTip> <div style="color: #ccc; font-size: 12px"> jpg/png files with a size less than 500kb </div> </template> <template #action="scope"> <el-button type="primary" @click="submitForm(scope)">提交</el-button> <el-button @click="resetForm">重置</el-button> </template> </lib-form>
表單項的配置數(shù)組:由于這配置數(shù)組比較長,所以一般可以單獨抽離出來,不要寫在vue文件中,這樣可以提高代碼的可讀性。
// 這里以多行表單布局為例子 let options: FormOptions[] = [ { type: 'row', rowGutter: 20, cols: [ { type: 'input', value: '', label: '用戶名', prop: 'username', placeholder: '請輸入用戶名', rules: [ { required: true, message: '用戶名不能為空', trigger: 'blur', }, { min: 2, max: 6, message: '用戶名在2-6位之間', trigger: 'blur', }, ], attrs: { clearable: true, }, colOption: { offset: 0, span: 12, }, }, { type: 'input', value: '', label: '用戶名', prop: 'username', placeholder: '請輸入用戶名', rules: [ { required: true, message: '用戶名不能為空', trigger: 'blur', }, { min: 2, max: 6, message: '用戶名在2-6位之間', trigger: 'blur', }, ], attrs: { clearable: true, }, colOption: { offset: 0, span: 12, }, }, ], }, ]
總結(jié)
UI組件二次封裝其實不難,只要我們能掌握基本語法,就可以根據(jù)業(yè)務(wù)場景去封裝我們需要的組件,然后在慢慢去完善這個組件的功能。只要遵循這些原則:命名規(guī)范、組件通用、特性繼承、場景通用、接口簡單、兼容性強(qiáng)、功能完善。
以上就是vue 封裝一個高質(zhì)量的表單通用組件的詳細(xì)內(nèi)容,更多關(guān)于vue 封裝表單通用組件的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
解決vue create 創(chuàng)建項目只有兩個文件問題
這篇文章主要介紹了解決vue create 創(chuàng)建項目只有兩個文件問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02vue引入jquery時報錯 $ is not defined的問題及解決
這篇文章主要介紹了vue引入jquery時報錯 $ is not defined的問題及解決,具有很好的參考價值,希望對大家有所幫助。2022-09-09vue使用jsonp抓取qq音樂數(shù)據(jù)的方法
這篇文章主要介紹了vue使用jsonp抓取qq音樂數(shù)據(jù)的方法,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-06-06Vue結(jié)合Element-Plus封裝遞歸組件實現(xiàn)目錄示例
本文主要介紹了Vue結(jié)合Element-Plus封裝遞歸組件實現(xiàn)目錄示例,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-04-04element tree懶加載:load="loadNode"只觸發(fā)一次的解決方案
本文主要介紹了element tree懶加載:load="loadNode"只觸發(fā)一次的解決方案,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08vue點擊按鈕跳轉(zhuǎn)到另一個vue頁面實現(xiàn)方法
這篇文章主要給大家介紹了關(guān)于vue點擊按鈕跳轉(zhuǎn)到另一個vue頁面的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-08-08