LoginSignup
5
2

More than 3 years have passed since last update.

thisのスコープ問題

Last updated at Posted at 2019-03-14

ただのスコープ問題ですが、忘れたときにあたふたするのでメモ。

index.js
var app = new Vue({
    el: "#posts",
    data: {
        posts: []
    },
    created: function() {
        axios.get("https://○○○/wp-json/wp/v2/posts/").then(function(response) {
            this.posts = response.data;
            console.log(this.posts)
        })
    }
});

// this.postsは[]のまま

then()の中ではthisの参照先が変わってしまうので、this.postsに値を代入してもdata内のpostsは変更されない。
then()の外で変数にthisを代入して、代入した変数をthen()の中で使用することで解決!

index.js
var app = new Vue({
    el: "#posts",
    data: {
        posts: []
    },
    created: function() {
        var self = this;
        axios.get("https://○○○/wp-json/wp/v2/posts/").then(function(response) {
            self.posts = response.data;
            console.log(self.posts)
        })
    }
});

単純なミスだけど、たまに
アワ((゚゚ωω゚゚ ))ワワ!!
ってなる。

5
2
0

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
5
2