设计思路
- 利用Vue Fragment特性:Vue Fragment 允许在不额外创建 DOM 元素的情况下包裹多个子元素,我们可以在 Fragment 内管理表单域组件。
- 表单域组件设计:每个表单域组件自身负责数据校验逻辑,例如输入框组件可以通过
watch
监听输入变化进行实时校验,并且提供一个方法来暴露当前校验结果。
- 表单提交逻辑:在表单组件中,通过
ref
引用各个表单域组件,在提交表单时遍历这些引用,调用每个表单域组件的校验方法,只有所有校验都通过才允许提交。
关键代码
- 表单域组件(以输入框为例)
<template>
<div>
<input v-model="inputValue" @input="validate">
</div>
</template>
<script>
export default {
data() {
return {
inputValue: '',
isValid: true
};
},
methods: {
validate() {
// 这里可以写具体的校验逻辑,例如非空校验
this.isValid = this.inputValue.length > 0;
},
getValidationResult() {
return this.isValid;
}
}
};
</script>
- 包含 Vue Fragment 的表单组件
<template>
<Fragment>
<FormField ref="field1" />
<FormField ref="field2" />
<button @click="submitForm">提交</button>
</Fragment>
</template>
<script>
import Fragment from 'vue-fragment';
import FormField from './FormField.vue';
export default {
components: {
Fragment,
FormField
},
methods: {
submitForm() {
const fieldRefs = this.$refs;
let allValid = true;
Object.keys(fieldRefs).forEach(key => {
if (!fieldRefs[key].getValidationResult()) {
allValid = false;
return false;
}
});
if (allValid) {
// 执行表单提交逻辑
console.log('表单提交');
} else {
console.log('表单校验未通过');
}
}
}
};
</script>