2017-12-07 5 views
1

私は以前この "問題"を扱っていましたが、実際に結果を正しく取得する方法は覚えていません。私はHTML側で読み込むことができる変数でいくつかのデータをロードするためにVueの2を使用しています:私はAxios関数スコープ(FC)でconsole.log(response.data)を記述する場合Vue.js 2&Axiosスコープの問題

window.Vue = require('vue'); 
window.axios = require('axios'); 

const app = new Vue({ 
    el: '#app', 
    data: { 
     operaciones: [], 
     sopts: [] 
    }, 
    created: function() { 
     this.loadOperationTypes(); 
     console.log(this.operaciones); <-- SC 
    }, 
    methods: { 
     loadOperationTypes: function() { 
      axios.post('/api/operaciones') 
      .then(response => { 
       console.log(response.data); <-- FC 
       this.operaciones = response.data 
      }) 
      .catch(error => { 
       this.operaciones = error; 
      }); 
     } 
    } 
}); 

それは印刷します。

enter image description here

私は created_ function() {}スコープで console.log(response.data)を書く場合

はしかし、それは印刷します

enter image description here

axios.post('/api/operaciones') 
.then(response => { 
    console.log(response.data); 
    app.operaciones = response.data 
}) 

そして

var $this = this; 
axios.post('/api/operaciones') 
.then(response => { 
    console.log(response.data); 
    $this.operaciones = response.data 
}) 

をしかし、任意の手掛かりと同じである:私はすでにこのようなを使用しようとしましたか?

ありがとうございます。

答えて

1

これは実際にスコープとは別の問題です。あなたの質問で試したソリューションのいずれかが正しくthis.operacionesに設定されます。問題は、非同期操作を処理していることです。 created

ライン

console.log(this.operaciones); 

常に空の配列を記録します。これは、loadOperationTypesが非同期操作を実行するためです。つまり、の時刻はです。

loadOperationTypesのすべてがconsole.logが実行される前に完了することを期待しているようですが、そうではありません。 loadOperationTypesはサーバーにpostを開始し、コードは継続してconsole.logを実行します。

の後でサーバから応答を受信すると、operacionesに応答が入力されます。

console.clear() 
 

 
const app = new Vue({ 
 
    el: '#app', 
 
    data: { 
 
     operaciones: [], 
 
     sopts: [] 
 
    }, 
 
    created: function() { 
 
     this.loadOperationTypes(); 
 
     console.log("THIS WILL ALWAYS BE AN EMPTY ARRAY", this.operaciones); 
 
    }, 
 
    methods: { 
 
     loadOperationTypes: function() { 
 
      axios.post('https://httpbin.org/post', ["some", "data"]) 
 
      .then(response => { 
 
       console.log("THIS SHOULD HAVE DATA", response.data.json); 
 
       this.operaciones = response.data.json 
 
      }) 
 
      .catch(error => { 
 
       this.operaciones = error; 
 
      }); 
 
     } 
 
    }, 
 
    watch: { 
 
     operaciones(newVal){ 
 
     console.log("THIS WILL HAVE DATA WHEN operaciones IS POPULATED", newVal) 
 
     } 
 
    } 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.1/axios.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script> 
 

 
<div id="app"></div>

+0

、私は完全に忘れてしまった、私はVueのインスペクタで今すぐチェックし、すべての情報があるようです。ありがとうございました。 – Maramal