4

my data fetch works fine when is used globally but once I stick in the single file component is not returning the items. What I'm doing wrong?

ladeditems.vue

<template>
<div>
  <ul v-for="item in items">
    <li>
      {{item.title}}
    </li>
  </ul>
</div>
</template>

<script>
export default {
  components: {'tiny-slider': VueTinySlider},
  name: 'ladeditems',
  data: {
    items: null
  },
  methods: {
    fetchData: function () {
      let self = this
      const myRequest = new Request('https://jsonplaceholder.typicode.com/posts')

      fetch(myRequest)
        .then((response) => { return response.json() })
        .then((data) => {
          self.items = data
          // console.log(self.items)
        }).catch( error => { console.log(error); });
    }
  },

  mounted() {
    this.fetchData()
  }
}
</script>
1
  • Where is the error? Try adding a catch to your fetch call Commented Dec 18, 2017 at 8:20

2 Answers 2

6

Your data declaration is incorrect, it should be like this:

data: function () {
  return {
    items: null
  }
}

This info is here: data. In short it has to be a function that returns an object. This should allow the property to be reactive to your changes.

Also worth noting that fetch isn't declared in the code you've provided so I assume it's a global declaration. If it isn't and it's a mixin then you'll need to scope it with this.fetch(...)

Sign up to request clarification or add additional context in comments.

Comments

3

https://v2.vuejs.org/v2/api/#data

When defining a component, data must be declared as a function that returns the initial data object, because there will be many instances created using the same definition. If we use a plain object for data, that same object will be shared by reference across all instances created! By providing a data function, every time a new instance is created we can call it to return a fresh copy of the initial data.

Comments

Your Answer

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.