// update_time: '' // 修改时间
},
fieldList: [
{label: '账号', value: 'account', type: 'input', required: true, validator: checkAccount},
{label: '密码', value: 'password', type: 'password', required: true, validator: checkPwd},
{label: '昵称', value: 'name', type: 'input', required: true},
{label: '性别', value: 'sex', type: 'select', list: 'sexList', required: true},
{label: '头像', value: 'avatar', type: 'slot', className: 'el-form-block'},
{label: '手机号码', value: 'phone', type: 'input', validator: checkPhone},
{label: '微信', value: 'wechat', type: 'input', validator: checkWechat},
{label: 'QQ', value: 'qq', type: 'input', validator: checkQQ},
{label: '邮箱', value: 'email', type: 'input', validator: checkEmail},
{label: '描述', value: 'desc', type: 'textarea', className: 'el-form-block'},
{label: '状态', value: 'status', type: 'select', list: 'statusList', required: true}
],
rules: {},
labelWidth: '120px'
}
实现验证方法
一: 循环字段列表,根据type判断是提示选择不能为空,还是输入不能为空
二:如果字段必填,则根据是否有自定义验证去生成验证规则
三: 字段非必填,有自定义规则生成验证
// 初始化验证数据
_initValidate (formInfo) {
const obj = {},
fieldList = formInfo.fieldList
// 循环字段列表
for (let item of fieldList) {
let type = item.type === 'select' ? '选择' : '输入'
if (item.required) {
if (item.validator) {
obj[item.value] = {
required: item.required,
validator: item.validator,
trigger: 'blur'
}
} else {
obj[item.value] = {
required: item.required,
message: '请' + type + item.label,
trigger: 'blur'
}
}
} else if (item.validator) {
obj[item.value] = {
validator: item.validator,
trigger: 'blur'
}
}
}
formInfo.rules = obj
}
使用
结合上面的字段设计,我在页面上的使用是这样的,大家可以根据自己的字段设计去修改,大致实现过程是这样的
// mixin中的方法, 初始化字段验证规则
this._initValidate(this.formInfo)怎么配置到全局
通过mixin配置,然后在页面中使用(个人使用的是mixin)
配置为全局方法在页面中调用
挂在到vue实例上,通过this即可访问
mixins例子
export default {
data () {
/**
* 页面上的可复用的验证规则
*/
// 验证号码格式
const CHECK_PHONE = (rule, value, callback) => {










