我在 vuejs 中按顺序执行函数/方法时遇到一些问题。我有三个功能,如:
MethodA: function(){
if(x = 1){
value1 = 2;
}
if (x ==2){
value2 = 4;
}
this.MethodB();
}
MethodB: function(){
Total value = value1 + value2;
}
MethodC: function (){
this.$http.get('api/getvalue').then(function(response){
this.set('somedata', response.data);
response.data.forEach(para){
if(para.id == 1){
this.MethodA();
}
if(para.id == 2){
this.MethodA();
}
}
});
}
ready: function(){
this.MethodC();
}
Run Code Online (Sandbox Code Playgroud)
我this.MethodB()只想在MethodC并MethodA完全执行之后执行。我怎样才能做到这一点?
您可以将 Javascript Promise 与 Vue.js 方法一起使用:
methodA: function() {
return new Promise(function(resolve, reject) {
//run all your methodA code here
...
resolve('MethodA finished');
});
},
methodB: function() {
return new Promise(function(resolve, reject) {
//run all your methodB code here
...
resolve('MethodB finished');
});
},
methodC: function() {
//run your methodC code
}
Run Code Online (Sandbox Code Playgroud)
现在,要仅在方法 A 和方法 B 完成时运行方法 C,您可以使用承诺.then并将它们链接在一起。例如:
ready: function() {
//save `this` to a variable just to make it easier to be accessed within the chain
let self = this;
//run methodA, then methodB...only then, methodC
self.methodA.then(function(resultA) {
console.log(resultA);
return self.methodB();
}).then(function(resultB) {
console.log(resultB);
self.methodC();
});
}
Run Code Online (Sandbox Code Playgroud)
注意:如果您在方法 A 或方法 B 中运行 AJAX 调用,请确保仅在收到响应时才解析承诺。在你的前任中:
this.$http.get('api/getvalue').then(function(response){
...
resolve('My method is now complete');
}
Run Code Online (Sandbox Code Playgroud)