前言:
在日常使用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 包裹?;镜慕Y(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:單個表單組件的標簽文本,類似原生的
<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 做對比,當找到目標父組件時就通過調(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> 標簽的 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ā)有不小幫助。