0

I'm getting a little bit confused by Vue JS and how it is working. I have the following component:

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

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

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

  methods: {
    fetchData: function() {
      client.getEntries()
      .then(entries => {
        this.careerData = entries.items;
      });
      for (var i = 0, len = this.careerData.length; i < len; i++) {
        console.log('Success');
      }
    }
  }
});

This line within my then() function assigns an Array to my data object careerData.

this.careerData = entries.items

When I try to run this for:

  for (var i = 0, len = this.careerData.length; i < len; i++) {
    console.log('Success');
  }

It doesn't work because this.careerData.length appears to have no data in it, it's just an empty array however when I try running my component within my HTML the data is displayed perfectly on the page.

Any idea where I might be going wrong here, it's as if I can't use this.careerData in any of my methods. Any idea why I can't access this data even known I have assigned it in my fetchData method already? It's very strange the data manages to get to the front end perfectly however I can't seem to use it anywhere else within my methods.

Thanks, Nick

1
  • I'm wonder why you are iterating twice through careerData array ? Basically why you are doing that inside fetchData method ? Commented Jan 23, 2017 at 16:13

1 Answer 1

3

You are running the for loop outside the then and since it's an async operator, the array is still empty when you run the for loop.

put it inside the then function:

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

         for (var i = 0, len = this.careerData.length; i < len; i++) {
            console.log('Success');
         }
      });

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

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.