0%

Element Ui 同时验证多个表单

需求:Element Ui 同时验证多个表单

  • 以下代码报错
    Promise 调用 this 有问题
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
let p1 = new Promise(function(resolve, reject) {
this.$refs["gerenformRefa"].validate(valid => {
if (valid) {
resolve();
}
});
});

let p2 = new Promise(function(resolve, reject) {
this.$refs["formRefb"].validate(valid => {
if (valid) {
resolve();
}
});
});

Promise.all([p1]).then(function() {
console.log("666");
});
  • 正确代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
let _this = this;
let p1 = new Promise(function(resolve, reject) {
_this.$refs["formRefa"].validate(valid => {
if (valid) {
resolve();
}
});
});

let p2 = new Promise(function(resolve, reject) {
_this.$refs["formRefb"].validate(valid => {
if (valid) {
resolve();
}
});
});

Promise.all([p1]).then(function() {
console.log("666");
});
  • 原因:
    promsie 里压根就读不到 this,可以理解:取不到全局变量,作用域的问题,promise 里的 this 和 vue 中的 this 指向不同,promise 外面定义 let _this = this ,然后在 promise 里使用 _this 就可以执行方法了