背景
对于form表单自定义校验,其实有的时候我们可以进行复用,从而避免重复代码
参考了一下网上的方法,大致有以下两种方法
方法1:通过自定义函数传参(推荐)
代码示例
- html代码
<template>
<el-form
:model="ruleForm"
status-icon
:rules="rules"
ref="ruleForm"
label-width="100px"
class="demo-ruleForm"
>
<el-form-item label="文本1" prop="text1">
<el-input type="text" v-model="ruleForm.text1"></el-input>
</el-form-item>
<el-form-item label="文本2" prop="text2">
<el-input type="text" v-model="ruleForm.text2"></el-input>
</el-form-item>
<el-form-item label="文本3" prop="text3">
<el-input type="text" v-model="ruleForm.text3"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
<el-button @click="resetForm('ruleForm')">重置</el-button>
</el-form-item>
</el-form>
</template>
- js代码
data() {
const validateLength = function (maxLen) {
return function (rule, value, callback) {
if (value.length > maxLen) {
callback(new Error(`长度最大为${maxLen}`));
} else {
callback();
}
};
};
return {
ruleForm: {
text1: "",
text2: "",
text3: "",
},
rules: {
text1: [{ validator: validateLength(3), trigger: "blur" }],
text2: [{ validator: validateLength(6), trigger: "blur" }],
text3: [{ validator: validateLength(9), trigger: "blur" }],
},
}
}
方法2: 通过bind
重新指定this
指向,完成传参
需要注意的是,此方法定义的validate函数不能通过es6的箭头形式指定,因为es6箭头函数会导致函数内部this指向vue实例,从而导致后续步骤出错
代码示例
- js代码
export default {
data() {
const validateLength = function (rule, value, callback) {
// 此处this指向自定义的对象,即可拿到自定义的maxLen进行不同的判断
if (value.length > this.maxLen) {
callback(new Error(`长度最大为${this.maxLen}`));
} else {
callback();
}
};
const text1Obj = {
maxLen: 4,
};
const text2Obj = {
maxLen: 6,
};
const text3Obj = {
maxLen: 8,
};
return {
ruleForm: {
text1: "",
text2: "",
text3: "",
},
rules: {
text1: [{ validator: validateLength.bind(text1Obj), trigger: "blur" }],
text2: [{ validator: validateLength.bind(text2Obj), trigger: "blur" }],
text3: [{ validator: validateLength.bind(text3Obj), trigger: "blur" }],
},
};
}