LoginSignup
10
6

More than 5 years have passed since last update.

axiosで値が取り出せない

Last updated at Posted at 2017-09-02

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さんありがとうございます)

10
6
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
6