Nick Maddren
Nick Maddren

Reputation: 661

Vue JS v-for not iterating over array

Hi guys I am using Vue JS to try and loop through my data. Here is my whole JS file:

var contentful = require('contentful');

var client = contentful.createClient({
  space: 'HIDDEN',
  accessToken: 'HIDDEN'
});

Vue.component('careers', {
  template: '<div><div v-for="career in careerData">{{ fields.jobDescription }}</div></div>',

  data: function() {
    return {
     careerData: []
    }
  },

  created: function() {
   this.fetchData();
  },

  methods: {
   fetchData: function() {
     client.getEntries()
     .then(function (entries) {
       // log the title for all the entries that have it
       entries.items.forEach(function (entry) {
         if(entry.fields.jobTitle) {
           this.careerData = entries.items;
         }
       })
     });
   }
  }
});

var app = new Vue({
  el: '#app'
});

I am using methods to access some data from Contentful, once it has grabbed the necessary data it is sent to my data object.

If I console.log(careerData); within my console the following data is returned:

enter image description here

So I'd expect if I used v-for within my template and tried iterating over careerData it would render correctly however on my front-end I am left with an empty div like so:

<div id="app"><div></div></div>

I am currently pulling my component into my HTML like so:

<div id="app">
  <careers></careers>
</div>

No errors are displayed within my console, can you think of any reason this might be happening?

Thanks, Nick

Upvotes: 1

Views: 1268

Answers (2)

rap-2-h
rap-2-h

Reputation: 32048

Several problems I think. As @dfsq said, you should use a arrow function if you want to keep context (this).

fetchData: function() {
  client.getEntries()
    .then(entries => {
      this.careerData = entries.items
    });
}

Then you may replace {{fields.jobDescription}} by {{career.fields.jobDescription}}, as @unholysheep wrote.

It may work. If it does not, you could add a this.$forceUpdate(); right after this.fetchData();

Upvotes: 1

dfsq
dfsq

Reputation: 193311

Use arrow function in forEach callback so you don't loose context:

fetchData: function() {
  client.getEntries()
    .then(entries => {
      this.careerData = entries.items
    });
}

Upvotes: 0

Related Questions