前言:
在日常使用vue開發(fā)WEB項目中,經(jīng)常會有提交表單的需求。我們可以使用 iview 或者 element 等組件庫來完成相關(guān)需求妒穴;但我們往往忽略了其中的實現(xiàn)邏輯宋税,如果想深入了解其中的實現(xiàn)細節(jié),本文章從0到1讼油,手把手教你封裝一個屬于自己的Form組件! 實例代碼 https://github.com/zhengjunxiang/vue-form
Form 組件概覽
表單類組件有多種杰赛,比如輸入框(Input)、單選(Radio)矮台、多選(Checkbox)等乏屯。在使用表單時,也會經(jīng)常用到數(shù)據(jù)校驗瘦赫,如果每次都寫校驗程序來對每一個表單的輸入值進行校驗辰晕,會很低效,因此需要一個能夠校驗基礎(chǔ)表單控件的組件确虱,也就是本節(jié)要完成的Form
組件含友。
Form
組件分為兩個部分,一個是外層的Form
表單域組件校辩,一組表單控件只有一個Form
窘问,而內(nèi)部包含了多個FormItem
組件,每一個表單控件都被一個FormItem
包裹宜咒』莺眨基本的結(jié)構(gòu)看起來像:
<!-- ./src/views/Form.vue -->
<iForm ref="form" :model="formData" :rules="rules">
<iFormItem label="名稱:" prop="name">
<iInput v-model="formData.name" ></iInput>
</iFormItem>
<iFormItem label="郵箱:" prop="mail">
<iInput v-model="formData.mail"></iInput>
</iFormItem>
<button @click="handleSubmit">提交</button>
<button @click="handleReset">重置</button>
</iForm>
Form 需要有輸入校驗,并在對應(yīng)的 FormItem 中給出校驗提示故黑,校驗我們會用到一個開源庫:async-validator儿咱。使用規(guī)則大概如下:
[
{ required: true, message: '不能為空', trigger: 'blur' },
{ type: 'email', message: '格式不正確', trigger: 'blur' }
]
required
表示必填項,message
表示校驗失敗時的提示信息场晶,trigger
表示觸發(fā)校驗的條件混埠,它的值有blur
和change
表示失去焦點和正在輸入時進行校驗。如果第一條滿足要求诗轻,再進行第二條的驗證岔冀,type
表示校驗類型,值為email
表示校驗輸入值為郵箱格式概耻,還支持自定義校驗規(guī)則使套。更詳細的用法可以參看它的文檔。
初始化項目
使用 Vue CLI 3 創(chuàng)建項目(具體使用可以查看官方文檔),同時下載 async-validator 庫鞠柄。
初始化項目完項目后侦高,在 src/components
下新建一個form
文件夾,并初始化兩個組件 form.vue
和 formItem.vue
和一個input.vue
厌杜,同時可以按照自己的想法配置路由奉呛。初始完項目后src
下的項目錄如下:
./src
├── App.vue
├── assets
│ └── logo.png
├── components
│ ├── form
│ │ ├── form.vue
│ │ └── formItem.vue
│ └── input.vue
├── main.js
├── mixins
│ └── emitter.js
├── router.js
└── views
└── Form.vue
接口實現(xiàn)
組件的接口來自三個部分:props
计螺、slots
、events
瞧壮。Form
和FormItem
兩個組件用來做輸入數(shù)據(jù)校驗登馒,用不到 events
。Form
的 slot
就是一系列的 FormItem
咆槽,FormItem
的 slot
就是具體的表單如: <iInput>
陈轿。
在 Form
組件中,定義兩個 props
:
-
model:表單控件綁定的數(shù)據(jù)對象秦忿,在校驗或重置時會訪問該數(shù)據(jù)對象對應(yīng)數(shù)據(jù)麦射,類型為
Object
。 -
rules:表單校驗規(guī)則灯谣,即上面介紹的
async-validator
所使用的校驗規(guī)則潜秋,類型為Object
。
在FormItem
組件中胎许,也定義兩個props
:
-
label:單個表單組件的標(biāo)簽文本峻呛,類似原生的
<label>
元素,類型為String
辜窑。 -
prop:對應(yīng)表單域
Form
組件model
里的字段杀饵,用于在校驗或重置時訪問表單組件綁定的數(shù)據(jù),類型為String
谬擦。
定義完后,調(diào)用頁面的代碼如下:
<template>
<div class="home">
<h3>Form (校驗表單)</h3>
<iForm ref="form" :model="formData" :rules="rules">
<iFormItem label="名稱:" prop="name">
<iInput v-model="formData.name"></iInput>
</iFormItem>
<iFormItem label="郵箱:" prop="mail">
<iInput v-model="formData.mail"></iInput>
</iFormItem>
</iForm>
</div>
</template>
<script>
// @ is an alias to /src
import iForm from '@/components/form/form.vue'
import iFormItem from '@/components/form/formItem.vue'
import iInput from '@/components/input.vue'
export default {
name: 'home',
components: { iForm, iFormItem, iInput },
data() {
return {
formData: { name: '', mail: '' },
rules: {
name: [{ required: true, message: '不能為空', trigger: 'blur'}],
mail: [
{ required: true, message: '不能為空', trigger: 'blur'},
{ type: 'email', message: '郵箱格式不正確', trigger: 'blur'}
]
}
}
}
}
</script>
代碼中的 iForm
朽缎、iFormItem
和 iInput
組件的實現(xiàn)細節(jié)將在后邊的內(nèi)容涉及惨远。
到此,iForm
和 iFormItem
組件的代碼如下:
<!-- ./src/components/form/form.vue -->
<template>
<div>
<slot></slot>
</div>
</template>
<script>
export default {
name: 'iForm',
data() {
return { fields: [] }
},
props: {
model: { type: Object },
rules: { type: Object }
},
created() {
this.$on('form-add', field => {
if (field) this.fields.push(field);
});
this.$on('form-remove', field => {
if (field.prop) this.fields.splice(this.fields.indexOf(field), 1);
})
}
}
</script>
<!-- ./src/components/form/formItem.vue -->
<template>
<div>
<label v-if="label">{{ label }}</label>
<slot></slot>
</div>
</template>
<script>
export default {
name: 'iFormItem',
props: {
label: { type: String, default: '' },
prop: { type: String }
}
}
</script>
在 iForm
組件中設(shè)置了 fields
數(shù)組來保存組件中的表單實例话肖,方便接下來獲取表單實例來判斷各個表單的校驗情況;
并在 created
生命周期中就綁定兩個監(jiān)聽事件 form-add
和 form-remove
用于添加和移除表單實例北秽。
接下來就是實現(xiàn)剛才提到綁定事件 ,但在實現(xiàn)之前我們要設(shè)想下最筒,我們要怎么調(diào)用綁定事件這個方法贺氓?
在 Vue.js 1.x 版本,有this.$dispatch
方法來綁定自定義事件床蜘,但在 Vue.js 2.x 里廢棄了辙培。但我們可以實現(xiàn)一個類似的方法,調(diào)用方式為 this.dispatch
少了 $
來于之前的舊 API 做區(qū)分邢锯。
我們可以把該方法單獨寫到 emitter.js
文件中扬蕊,然后通過組件中的 mixins
方式引用,達到代碼復(fù)用丹擎。在 src
中創(chuàng)建文件夾 mixins
然后在其中創(chuàng)建 emitter.js
尾抑,具體代碼如下:
<!-- ./src/mixins/emitter.js -->
export default {
methods: {
dispatch(componentName, eventName, params) {
let parent = this.$parent || this.$root;
let name = parent.$options.name;
while (parent && (!name || name !== componentName)) {
parent = parent.$parent;
if (parent) name = parent.$options.name;
}
if (parent) parent.$emit.apply(parent, [eventName].concat(params));
}
}
}
可以看到該 dispatch
方法通過遍歷組件的 $parent.name
來和傳入的參數(shù) componentName
做對比歇父,當(dāng)找到目標(biāo)父組件時就通過調(diào)用父組件的 $emit
來觸發(fā)參數(shù) eventName
對應(yīng)的綁定事件。
接下來在 formItem.vue
中通過 mixins
引入 dispatch
方法再愈,實現(xiàn)觸發(fā)綁定事件 form-add
和 form-remove
, 代碼如下:
<!-- ./src/components/form/formItem.vue -->
<template>
<div>
<label v-if="label">{{ label }}</label>
<slot></slot>
</div>
</template>
<script>
import Emitter from '@/mixins/emitter.js';
export default {
name: 'iFormItem',
mixins: [ Emitter ],
props: {
label: { type: String, default: '' },
prop: { type: String }
},
mounted() {
if (this.prop) {
this.dispatch('iForm', 'form-add', this);
}
},
// 組件銷毀前榜苫,將實例從 Form 的緩存中移除
beforeDestroy () {
this.dispatch('iForm', 'form-remove', this);
},
}
</script>
接下來是實現(xiàn) formItem.vue
的輸入數(shù)據(jù)校驗功能,在校驗是首先需要知道校驗的規(guī)則翎冲,所以我們先要拿到 Form.vue
中的 rules
對象垂睬。
- 在
Form.vue
中rules
對象通過props
傳給iForm
組件,那么我們可以在iForm
組件中通過provide
的方式導(dǎo)出該組件實例府适,讓子組件可以獲取到其props
中的rules
對象羔飞; - 子組件
formItem
可以通過inject
的方式注入需要訪問的實例;
此時代碼如下:
<!-- ./src/components/form/form.vue -->
...
export default {
name: 'iForm',
data() {
return { fields: [] }
},
props: {
model: { type: Object },
rules: { type: Object }
},
provide() {
return { form: this }
},
created() {
this.$on('form-add', field => {
if (field) this.fields.push(field);
});
this.$on('form-remove', field => {
if (field.prop) this.fields.splice(this.fields.indexOf(field), 1);
})
}
}
</script>
<!-- ./src/components/form/formItem.vue -->
...
import Emitter from '@/mixins/emitter.js';
export default {
name: 'iFormItem',
mixins: [ Emitter ],
inject: [ 'form' ],
props: {
label: { type: String, default: '' },
prop: { type: String }
},
mounted() {
if (this.prop) {
this.dispatch('iForm', 'form-add', this);
}
},
// 組件銷毀前檐春,將實例從 Form 的緩存中移除
beforeDestroy () {
this.dispatch('iForm', 'form-remove', this);
},
}
</script>
現(xiàn)在在 formItem
中就可以通過 this.form.rules
來獲取到規(guī)則對象了逻淌;
有了規(guī)則對象以后,就可以設(shè)置具體的校驗方法了疟暖;
- setRules: 設(shè)置具體需要監(jiān)聽的事件卡儒,并觸發(fā)校驗;
- getRules:獲取該表單對應(yīng)的校驗規(guī)則俐巴;
- getFilteredRule:過濾出符合要求的 rule 規(guī)則骨望;
-
validate:具體的校驗過程;
...
具體代碼如下:
<!-- ./src/components/form/formItem.vue -->
<template>
<div>
<label :for="labelFor" v-if="label" :class="{'label-required': isRequired}">{{label}}</label>
<slot></slot>
<div v-if="isShowMes" class="message">{{message}}</div>
</div>
</template>
<script>
import AsyncValidator from 'async-validator';
import Emitter from '@/mixins/emitter.js';
export default {
name: 'iFormItem',
mixins: [ Emitter ],
inject: [ 'form' ],
props: {
label: { type: String, default: '' },
prop: { type: String }
},
data() {
return {
isRequired: false, isShowMes: false, message: '', labelFor: 'input' + new Date().valueOf()
}
},
mounted() {
if (this.prop) {
this.dispatch('iForm', 'form-add', this);
// 設(shè)置初始值
this.initialValue = this.fieldValue;
this.setRules();
}
},
// 組件銷毀前欣舵,將實例從 Form 的緩存中移除
beforeDestroy () {
this.dispatch('iForm', 'form-remove', this);
},
computed: {
fieldValue() {
return this.form.model[this.prop]
}
},
methods: {
setRules() {
let rules = this.getRules();
if (rules.length) {
rules.forEach(rule => {
if (rule.required !== undefined) this.isRequired = rule.required
});
}
this.$on('form-blur', this.onFieldBlur);
this.$on('form-change', this.onFieldChange);
},
getRules() {
let formRules = this.form.rules;
formRules = formRules ? formRules[this.prop] : [];
return formRules;
},
// 過濾出符合要求的 rule 規(guī)則
getFilteredRule (trigger) {
const rules = this.getRules();
return rules.filter(rule => !rule.trigger || rule.trigger.indexOf(trigger) !== -1);
},
/**
* 校驗表單數(shù)據(jù)
* @param trigger 觸發(fā)校驗類型
* @param callback 回調(diào)函數(shù)
*/
validate(trigger, cb) {
let rules = this.getFilteredRule(trigger);
if(!rules || rules.length === 0) return true;
// 使用 async-validator
const validator = new AsyncValidator({ [this.prop]: rules });
let model = {[this.prop]: this.fieldValue};
validator.validate(model, { firstFields: true }, errors => {
this.isShowMes = errors ? true : false;
this.message = errors ? errors[0].message : '';
if (cb) cb(this.message);
})
},
resetField () {
this.message = '';
this.form.model[this.prop] = this.initialValue;
},
onFieldBlur() {
this.validate('blur');
},
onFieldChange() {
this.validate('change');
}
}
}
</script>
<style>
.label-required:before {
content: '*';
color: red;
}
.message {
font-size: 12px;
color: red;
}
</style>
注意:這次除了增加了具體的校驗方法外擎鸠,還有錯誤提示信息的顯示邏輯 <label>
標(biāo)簽的 for
屬性設(shè)置;到此缘圈,formItem
組件完成劣光。
有了 formItem
組件我們就可以用它了包裹 input
組件:
- 在
input
組件中通過@input
和@blur
這兩個事件來觸發(fā)formItem
組件的form-change
和form-blur
的監(jiān)聽方法。需要特別注意:在handleInput
中需要調(diào)用this.$emit('input', value)
糟把,把input
中輸入的value
傳給在實例調(diào)用頁面中的formData
绢涡,代碼如下:
<!-- ./src/views/Form.vue -->
// 省略部分代碼
<template>
<div class="home">
<h3>Form (校驗表單)</h3>
<iForm ref="form" :model="formData" :rules="rules">
<iFormItem label="名稱:" prop="name">
<iInput v-model="formData.name"></iInput>
</iFormItem>
<iFormItem label="郵箱:" prop="mail">
<iInput v-model="formData.mail"></iInput>
</iFormItem>
</iForm>
</div>
</template>
<script>
// @ is an alias to /src
import iForm from '@/components/form/form.vue'
import iFormItem from '@/components/form/formItem.vue'
import iInput from '@/components/input.vue'
// formData中的數(shù)據(jù)通過v-model的方試進行綁定,
// 在 input 組件中調(diào)用 this.$emit('input', value) 把數(shù)據(jù)傳給 formData
export default {
name: 'home',
components: { iForm, iFormItem, iInput },
data() {
return {
formData: { name: '', mail: '' }
}
}
}
</script>
- 并在組件中
watch
其輸入的value
值遣疯,賦值給input
組件雄可;
實現(xiàn)代碼如下:
<!-- ./src/components/input.vue -->
<template>
<div>
<input ref="input" :type="type" :value="currentValue" @input="handleInput" @blur="handleBlur" />
</div>
</template>
<script>
import Emitter from '@/mixins/emitter.js';
export default {
name: 'iInput',
mixins: [ Emitter ],
props: {
type: { type: String, default: 'text'},
value: { type: String, default: ''}
},
watch: {
value(value) {
this.currentValue = value
}
},
data() {
return { currentValue: this.value, id: this.label }
},
mounted () {
if (this.$parent.labelFor) this.$refs.input.id = this.$parent.labelFor;
},
methods: {
handleInput(e) {
const value = e.target.value;
this.currentValue = value;
this.$emit('input', value);
this.dispatch('iFormItem', 'form-change', value);
},
handleBlur() {
this.dispatch('iFormItem', 'form-blur', this.currentValue);
}
}
}
</script>
input
組件到此就完成,現(xiàn)在我們可以接著在 form
組件實現(xiàn)表單提交時缠犀,校驗所有表單数苫,和重置所用表單的功能了:
<!-- ./src/components/form/form.vue -->
<template>
<div>
<slot></slot>
</div>
</template>
<script>
export default {
name: 'iForm',
data() {
return { fields: [] }
},
props: {
model: { type: Object },
rules: { type: Object }
},
provide() {
return { form: this }
},
methods: {
resetFields() {
this.fields.forEach(field => field.resetField())
},
validate(cb) {
return new Promise(resolve => {
let valid = true, count = 0;
this.fields.forEach(field => {
field.validate('', error => {
if (error) valid = false;
if (++count === this.fields.length) {
resolve(valid);
if (typeof cb === 'function') cb(valid);
}
})
})
})
}
},
created() {
this.$on('form-add', field => {
if (field) this.fields.push(field);
});
this.$on('form-remove', field => {
if (field.prop) this.fields.splice(this.fields.indexOf(field), 1);
})
}
}
</script>
- validate: 獲取所有表單的校驗結(jié)果,并做對應(yīng)邏輯處理辨液;
- resetFields: 重置所有表單文判;
現(xiàn)在讓我們回到最初的調(diào)用頁面 ./src/views/Form.vue
下,添加兩個按鈕室梅,分別用于提交表單和重置表單:
<!-- ./src/views/Form.vue -->
<template>
<div class="home">
<h3>Form (校驗表單)</h3>
<iForm ref="form" :model="formData" :rules="rules">
<iFormItem label="名稱:" prop="name">
<iInput v-model="formData.name"></iInput>
</iFormItem>
<iFormItem label="郵箱:" prop="mail">
<iInput v-model="formData.mail"></iInput>
</iFormItem>
<button @click="handleSubmit">提交</button>
<button @click="handleReset">重置</button>
</iForm>
</div>
</template>
<script>
// @ is an alias to /src
import iForm from '@/components/form/form.vue'
import iFormItem from '@/components/form/formItem.vue'
import iInput from '@/components/input.vue'
export default {
name: 'home',
components: { iForm, iFormItem, iInput },
data() {
return {
formData: { name: '', mail: '' },
rules: {
name: [{ required: true, message: '不能為空', trigger: 'blur'}],
mail: [
{ required: true, message: '不能為空', trigger: 'blur'},
{ type: 'email', message: '郵箱格式不正確', trigger: 'blur'}
]
}
}
},
methods: {
handleSubmit() {
this.$refs.form.validate((valid) => {
if (valid) console.log('提交成功');
else console.log('校驗失敗');
})
},
handleReset() { this.$refs.form.resetFields() }
}
}
</script>
到此戏仓,Form
組件的基本功能就已經(jīng)完成疚宇,雖然,只是簡單的幾個表單控件赏殃,但其已經(jīng)實現(xiàn)檢驗和提示功能敷待。
結(jié)語
通過自己封裝組件可以對 Vue.js 的組件來進一步加深理解,如 provide / inject 和 dispatch 通信方法的使用場景仁热。對以后的開發(fā)有不小幫助榜揖。