最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get json with Vue and Fetch Api - Stack Overflow

programmeradmin2浏览0评论

I have a simple code based on Vue.js:

const app = new Vue({
    el: 'vue-app',
    data: {
        displayedBooks: {}
    },
    created() {
        fetch('/library').then(response => response.json())
            .then((data) => this.data.displayedBooks = data);
    }
});

But I got an exception:

Uncaught (in promise) TypeError: Cannot set property 'displayedBooks' of undefined at fetch.then.then (main.js:8)

Why this simple code is not works well?

I have a simple code based on Vue.js:

const app = new Vue({
    el: 'vue-app',
    data: {
        displayedBooks: {}
    },
    created() {
        fetch('/library').then(response => response.json())
            .then((data) => this.data.displayedBooks = data);
    }
});

But I got an exception:

Uncaught (in promise) TypeError: Cannot set property 'displayedBooks' of undefined at fetch.then.then (main.js:8)

Why this simple code is not works well?

Share Improve this question edited Feb 24, 2019 at 6:11 Daniel 2,7772 gold badges21 silver badges37 bronze badges asked Feb 23, 2019 at 19:07 Aleks BeAleks Be 731 gold badge1 silver badge11 bronze badges 4
  • 4 It'd just be this.displayedBooks, not this.data.displayedBooks. Everything in your Vue data parameter gets attached to this directly. – ceejayoz Commented Feb 23, 2019 at 19:19
  • 3 This is a plain typo: it should be this.displayedBooks = data :) – Terry Commented Feb 23, 2019 at 19:21
  • 1 Another gotcha can be that "this" in this.data.displayedBooks can be the Ajax library and not the Vue instance. If this is the problem then define: var vm = this; then use vm.data.displayedBooks for where to pass the data back to. – WillC Commented Feb 23, 2019 at 23:23
  • Here, in ments a got a all answers! Use this.displayedBooks and don't forget about store context with var self = this in created() function – Aleks Be Commented Feb 24, 2019 at 6:16
Add a ment  | 

2 Answers 2

Reset to default 2

It'd just be this.displayedBooks, not this.data.displayedBooks. Everything in your Vue data parameter gets attached to this directly.

const app = new Vue({
    el: 'vue-app',
    data: {
        displayedBooks: {}
    },
    created() {
        fetch('/library').then(response => {
            this.displayedBooks = response.data
    }, error =>{
       console.log(error)
   })
});

发布评论

评论列表(0)

  1. 暂无评论