vue elementui前端异步方法转同步记录
element
A Vue.js 2.0 UI Toolkit for Web
项目地址:https://gitcode.com/gh_mirrors/eleme/element
·
elementui的表单验证功能

表单验证方法如果传入回调函数时是异步的
// 子组件的方法
validateForm(){
this.$refs.jsonEditor.getRef("form").validate((valid, hints) => {
return {valid: valid, hints: hints}
})
}
// 父组件调用,会发现校验结果,hints为undefine
submitAll(){
this.$refs.resourceEditorRef.forEach((item, index) => {
console.log(item.validateForm())
})
}
修改成同步的
// 子组件方法
validateForm(){
// this.$refs.jsonEditor.getRef("form").validate((valid, hints) => {
// return {valid: valid, hints: hints}
// })
// return new Promise((resolve, reject) => {
// this.$refs.jsonEditor.getRef("form").validate((valid, hints) => {
// resolve({valid, hints})
// })
// })
//或者根据官网文档说明可以不传入回调函数,直接validate
return this.$refs.jsonEditor.getRef("form").validate
},
// 父组件调用
submitAll(){
// this.$refs.resourceEditorRef.forEach((item, index) => {
// console.log("校验结果", item.validateForm())
// })
this.$refs.resourceEditorRef.forEach(async (item, index) => {
let {valid, hints} = await item.validateForm()
console.info(valid, hints)
console.log("校验结果", hints)
})
}
但是其实上面 submitAll 的 forEach 是有问题, 需要改成传统的for遍历, 因为 forEach 的入参是一个回调函数 , 简单的说就是执行 forEach 后会马上执行forEach后面的代码

所以修改成普通的for , 使用普通 for 循环的时候有需要多包一层
// 子组件方法
validateForm(){
//或者根据官网文档说明可以不传入回调函数,直接validate
return this.$refs.jsonEditor.getRef("form").validate
}
//父组件调用
submitAll(){
(async () => {
let submitAllForm = {};
for (let index = 0; index < this.$refs.resourceEditorRef.length; index++) {
const item = this.$refs.resourceEditorRef[index]
await item.validateForm().then(res => {
console.log("表单校验",res)
}).catch(res => {
console.log("表单校验catch",res)
if(res == false){
this.$message({ type: "error", message: "表单校验失败" });
// 有一个校验失败则直接返回
return;
}
})
}
//后续操作
})()
}
或者
// 子组件方法
validateForm(){
return new Promise((resolve, reject) => {
this.$refs.jsonEditor.getRef("form").validate((valid, hints) => {
resolve({valid, hints})
})
})
}
// 父调用
submitAll(){
(async () => {
let submitAllForm = {};
for (let index = 0; index < this.$refs.resourceEditorRef.length; index++) {
const item = this.$refs.resourceEditorRef[index]
let {valid, hints} = await item.validateForm();
console.log("表单校验valid",valid)
console.log("表单校验hints",hints)
debugger
}
//后续操作
debugger
})()
}
A Vue.js 2.0 UI Toolkit for Web
最近提交(Master分支:4 个月前 )
c345bb45
1 年前
a07f3a59
* Update transition.md
* Update table.md
* Update transition.md
* Update table.md
* Update transition.md
* Update table.md
* Update table.md
* Update transition.md
* Update popover.md 1 年前
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)