Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data Fetch in Vue.js Single File Component

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>
like image 657
Ben Avatar asked Jan 03 '23 01:01

Ben


1 Answers

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(...)

like image 163
webnoob Avatar answered Jan 05 '23 15:01

webnoob