axiosで値が取り出せずに2時間ほど悩みました。vueと一緒に使っています。
はじめの動かないコードはこちら
<div id="app">
<form>
<input v-model="query" placeholder="query"><button v-on:click.prevent="fetch">送信</button>
</form>
<p>{{ text }}</p>
</div>
var app = new Vue({
el: '#app',
data: {
query: '',
text: '',
},
methods:
{
fetch: function (event) {
axios({
method: 'post',
url: '<URL>',
data: {
query: this.query,
},
})
.then(function (response) {
this.text = response.data.text;
})
.catch(function (error) {
console.log(error);
});
},
},
})
.thenの後、this.dataがundifinedになっていました。Vueの中にaxiosが入れ子になっているため、参照できていませんでした。
修正後は次です
var app = new Vue({
el: '#app',
data: {
query: '',
text: '',
},
methods:
{
fetch: function (event) {
var self = this; // 追加
axios({
method: 'post',
url: '<URL>',
data: {
query: this.query,
},
})
.then(function (response) {
self.data.text = response.data.text; // ここ修正
})
.catch(function (error) {
console.log(error);
});
},
},
})
ES2015
ES2015以降の新たなJavaScriptでは、function()のかわりに()=>記法を利用することにより、function内でもthisを引き継いで利用できるそうです(potato4dさんありがとうございます)