封装element表单组件- 如何在外部获取组件的校验结果以及获取表单信息
// 返回表单数据
getFormInfo(needRuleFlag = true) {
if (!needRuleFlag) {
return { ...this.ruleForm }
}
return this.$refs.ruleFormRef.validate((valid, fields) => {
if (valid) {
// 验证通过,可以执行提交操作
console.log('==>验证通过', this.ruleForm)
return { ...this.ruleForm } // 注意 返回的都是true
} else {
for (let field in fields) {
if (fields.hasOwnProperty(field)) {
const element = document.getElementsByClassName(`is-error`)
if (element && element[0]) {
element[0].scrollIntoView({ behavior: 'smooth', block: 'center' })
break // 只滚动到第一个错误字段
}
}
}
// 验证不通过,处理错误
return false
}
})
},
// 验证返回true时候 再返回数据
getFormInfoReturn() {
return this.ruleForm
}