最近在开发一个移动端商城项目,用到了有赞的 vant ,因为最近大都采用 element ui 在做PC端的东西,对比来说,vant的完成度还是偏低了点,很多细节都虽然都实现了接口,但是想使用得自己去想办法,没办法拿来即用。昨天用到 Uploader 图片上传 如是,提供了file回调,却没有提供上传功能,我必须给他加2个函数实现axios提交才能用,还有今天用到表单验证这块,它的 Field组件 虽然给了error-message的错误提示接口,但是没有内置表单验证功能。
element ui 采用async-validator 实现表单验证,我也基于这个组件进行扩展,async-validator不支持细粒化验证,于是先对它进行扩展
validator.js
import asyncValidator from 'async-validator'
class validator {
constructor(rules, data) {
this.setData(data);
this.setRules(rules);
}
setData(data) {
this.data = data;
}
setRules(rules, {cover} = {}) {
if (cover === undefined || cover) {
this.validators = {};
}
for (let attr in rules) {
const rule = {};
rule[attr] = rules[attr];
this.validators[attr] = new asyncValidator(rule);
}
}
validate(callback, data) {
let cb,d;
if (typeof callback === 'function' ){
cb = callback;
d = data;
}else if (typeof data === 'function' ){
cb = data;
d = callback;
}
let _d = d;
if (this.data) {
if (!d) {
_d = this.data;
} else if (typeof d === 'string') {
_d = {};
_d[d] = this.data[d]
} else if (Array.isArray(d)) {
_d = {};
d.forEach(attr => {
_d[attr] = this.data[attr]
})
}
}
const err = [];
if (_d) {
for (let attr in _d) {
if (this.validators[attr]) {
const o = {};
o[attr] = _d[attr];
this.validators[attr].validate(o, (error) => {
if (error) {
err.push(error[0])
}
})
}
}
}
cb && cb(err.length > 0, err)
}
}
export default function (rules, data) {
return new validator(rules, data)
}
demo.vue
{{ countdown ? countdown + 's' : '发送'}} 立即注册 重置
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



