【问题标题】:Calling function sequentially in vuejs在 vuejs 中按顺序调用函数
【发布时间】:2016-08-01 10:02:14
【问题描述】:

我在 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();
}

我想在MethodCMethodA 完全执行后才执行this.MethodB()。我怎样才能做到这一点?

【问题讨论】:

  • 我编辑了您的问题,写作MethodC,但现在我不确定您的意思。您能否解释一下,如果 Method 彼此循环依赖,您希望它们如何在其他人之前/之后执行?
  • 我会使用 Promise.then 来链接调用。

标签: laravel-5 vue.js


【解决方案1】:

您可以将 Javascript Promises 与 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
}

现在,要仅在 methodA 和 methodB 完成时运行 methodC,您可以使用 Promise .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();
    });
}

注意:如果您在 methodA 或 methodB 中运行 AJAX 调用,请确保仅在收到响应时才解析 Promise。在你的前任中:

this.$http.get('api/getvalue').then(function(response){ 
    ...
    resolve('My method is now complete'); 
}

【讨论】:

  • @TashiTobgay 不客气 :) Javascript 承诺非常适合异步代码控制。
猜你喜欢
  • 2012-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-11
相关资源
最近更新 更多