2016-09-10 7 views
2

私は現在Vuejsにwebappを開発中です。VueJS Mixinの値を返す方法

export default { 

    data() { 
    return { 
     apiURL: 'http://example.com/api', 
     timeout: 10000, 
    }; 
    }, 

    methods: { 

    callAPI(method, url, body) { 
     this.$http({ 
     url: this.apiURL + url, 
     method, 
     body, 
     timeout: this.timeout, 
     }) 
     .then((response) => 
     response, 
     (response) => { 
     if (response.data.error) { 
      this.error = response.data.error; 
     } else { 
      this.error = 'We can\'t connect to the server. Please try again in a few minutes.'; 
     } 
     return response; 
     }); 
     // return 'test'; 
    }, 

    }, 

}; 

は今、私のコンポーネントの一部では、私はAPI関数を呼び出します:私は、私は私のAPIへのリクエストを処理するグローバルアクセスできるようにミックスインを作成し

const api_response = this.callAPI('POST', '/auth', credentials); 
alert (api_response); 

それは正常に動作しますが、1事は期待どおりに機能しません。 api_response定数の値がresponseであることが期待されますが、常にundefinedです。だから毎回私はundefinedでこの警告を受け取りました。そんなことがあるものか?私はreturn 'test'行のコメントを解除すると、それは動作します:私はtestとの警告を得たが、this.$http一部内で動作するようには思えない...

答えて

1

あなたcallAPIにはreturn文を持っていないので、undefinedを返します。それはあなたの$http呼び出しを返された場合、あなたがしたいと思うので、それはまだ、あなたにresponseを与えないだろうが、a Promiseだろう

let api_response; 
this.callAPI('POST', '/auth', credentials).then((response) => api_response = response); 
+0

のようなものをありがとうございます。もう一つのオプションは 'return thisを実行することです。$ http({...' – Jordy

+0

これを返すと$ http({...}は値ではなくPromiseを取得します。 –

関連する問題