共计 2209 个字符,预计需要花费 6 分钟才能阅读完成。
置信很多人都有过这样的代码
{
name: [{ required: true, message: '请输出流动名称', trigger: 'blur'},
],
region: [{ required: true, message: '请抉择流动区域', trigger: 'change'}
],
}
额滴恶瓜脑膜炎上帝啊,这是要坐实我搬砖皇帝的身份么,一个 required 要我写这么多代码?我就一个必填,你默认给我整个英文,还是
name is required
唉,不得不想出点脑瓜仁不便不便了。
二话不说,
我包装了下 el-form, 看下:
<template>
<el-form ref="form" v-bind="$attrs" :rules="defaultRules" size="small">
<slot></slot>
</el-form>
</template>
<script>
import validator from "./validator";
/**
* Basic Form Components
*/
export default {
inheritAttrs: false,
data() {
return {defaultRules: {}, // Default configuration made by interception
validateList: [],};
},
created() {
// 读取规定列表
this.readRuleList();
const arr = this.$slots.default.map(v => ({
...v.componentOptions.propsData,
...v.data.attrs
}));
arr.forEach(v => {if (Object.prototype.hasOwnProperty.call(v, "required")) {if (!this.defaultRules[v.prop]) {this.$set(this.defaultRules, v.prop, []);
}
this.defaultRules[v.prop].push({
required: true,
message: `${v.label} 不能为空 `, // 重点这句
trigger: "blur"
});
}
this.validateList.forEach(val => {if (Object.prototype.hasOwnProperty.call(v, val)) {if (!this.defaultRules[v.prop]) {this.$set(this.defaultRules, v.prop, []);
}
this.defaultRules[v.prop].push({validator: validator[val](this),
trigger: "blur"
});
}
});
});
},
methods: {validate(fn) {return this.$refs.form.validate(fn);
},
reset() {this.$refs.form.resetFields();
},
readRuleList() {this.validateList = Object.keys(require("./validator/index").default);
}
}
};
</script>
这么用:
<base-form>
<el-form-item prop="title" label="题目" required>
<el-input v-model="addForm.title"></el-input>
</el-form-item>
</base-form>
就只有在 form-item 上写个 required! message 默认就是题目不能为空
当然这个 base-form 还能够轻易加定好的属性,你看:
validator.js
/**
* Verifier
*/
export default {mobile: () => (rule, value, callback) => {if (!/^1[0-9]{10}$/.test(value)) {callback(new Error("手机号码谬误"));
} else {callback();
}
},
email: () => (rule, value, callback) => {if (!/[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {callback(new Error("电子邮箱格局谬误"));
} else {callback();
}
}
};
你只有这么应用:
<base-form>
<el-form-item prop="title" label="题目" email>
<el-input v-model="addForm.title"></el-input>
</el-form-item>
</base-form>
邮箱验证就加上去啦!
当当当然,阔以叠加
<base-form>
<el-form-item prop="title" label="题目" email required>
<el-input v-model="addForm.title"></el-input>
</el-form-item>
</base-form>
ohohohohohohohoh!!
当当当当当当然,base-form 是不会冲掉本来 el-form 的属性的,这么炫炫的组件不 copy 试试吗?
正文完
发表至: javascript
2020-07-21