1

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?

Daniel
2,7772 gold badges22 silver badges37 bronze badges
asked Feb 23, 2019 at 19:07
4
  • 4
    It'd just be this.displayedBooks, not this.data.displayedBooks. Everything in your Vue data parameter gets attached to this directly. Commented Feb 23, 2019 at 19:19
  • 3
    This is a plain typo: it should be this.displayedBooks = data :) 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. Commented Feb 23, 2019 at 23:23
  • Here, in comments a got a all answers! Use this.displayedBooks and don't forget about store context with var self = this in created() function Commented Feb 24, 2019 at 6:16

2 Answers 2

2

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

answered Feb 26, 2019 at 9:58

Comments

1

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

MisterJames
3,3261 gold badge32 silver badges49 bronze badges
answered May 8, 2020 at 17:50

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.