浅谈vux之x-input使用以及源码解读

2020-06-14 06:22:15易采站长站整理

我们需要初始化值,但是会发现如果我们设置了required后校验还是会触发。如何让数据清空并且让校验也清空。

解决方法:

文档中写了reset可以重置输入框值,清除错误信息

使用方式:

在x-input外层的group标签上绑定ref来访问子组件。因此我们可以通过 this.$refs.group.$children获取到input组件集合并且可以使用组件中定义的reset方法

如果你的项目中已经安装了vux可以通过安装Search node_modules查找node_modules文件夹中vux安装包路径为

vux/src/components/x-input/index.vue
文件 reset方法源码如下:


reset(value = '') {
this.dirty = false
this.currentValue = value
this.firstError = ''
this.valid = true
}

回到我们的业务逻辑中当我们点击提交按钮时代码如下


onSubmitClick() {
if (!this.isInvalid) {
this.$refs.group.$children.forEach(child => {
child.reset()
})
} else {
// 展示提示信息
this.isShowToast = true
}

本以为这样就可以清空数据了,没想到点击按钮时数据是清空了,但是还是有报错图标显示。

 

通过 vue-devtools可以看到

valid的值为false查看vux源码查看涉及到valid代码如下


validate() {
// ...省略与本次无关的校验方法
if (!this.currentValue && this.required) {
this.valid = false
this.errors.required = '必填哦'
this.getError()
return
if (typeof this.isType === 'function') {
/*
取出自定义函数中的校验结果 是一个Boolean
checkNameValid(name) {
return {
valid: name === '三只萌新',
msg: '你不是萌新'
}
}
*/
const validStatus = this.isType(this.currentValue)
this.valid = validStatus.valid
if (!this.valid) {
// 如果校验值无效将自定义校验的msg赋值给errors对象下的format
this.errors.format = validStatus.msg
this.forceShowError = true
this.getError()
return
} else {
// 如果校验值有效则将error对象下的format删除
delete this.errors.format
}
// 如果都符合将valid赋值为有效
this.valid = true
}
}

validate函数校验当前是否有值,是否为必填,

如果当前值的校验方式是函数,将校验结果赋值给valid
。如果valid是false则将自定义的msg统一存储在errors对象下,
errors是用来存储不同类型的错误信息