1

I'm new to Vue.js and trying to display data that is requested from a server. I have created a new Vue app and defined a method:

methods: {
  getData: function() {
    // making a request, parsing the response and pushing it to the array.
    console.log(arr);
    return arr;
    }
  }

The method works OK and I can log the array to the console on a button click.

<button v-on:click="getData">Get me some data</button>

However, I'm not sure how to actually use this array in the app. I would like save it to a property and then display it for the user. At first, I was thinking that I could use computed properties like this:

computed: {
  values: function() {
    return this.getData;
  }
}

... and display it to the user with a for loop:

<p v-for="value in values">{{ value }}></p>

At least this solution did not produce the desired result. I've probably misunderstood some of Vue's logic here.

1 Answer 1

1

You need to use data property.

data() {
   return {
       values: []
   }
},

methods: {
   getData: function() {
       this.values = arr;
   }
}

And loop the values

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

4 Comments

Thanks, this works and I can see from the console that the values array is updated accordingly. However, it seems that Vue cannot detect these changes to an array and the fetched values are not displayed on front-end (just showing the initial, empty array). Any ideas on this?
Are you sure you have assigned the fetched data to the values?
Yes, I changed the logic as follows. ``` data() { return { values: [] } }, methods: { getData: function() { this.values = arr; console.log(this.values); // I can see the fetched data on console. } } ``` I think that the problem is that my app doesn't re-render the HTML document when the values array is updated. <p v-for="value in values">{{ value }}></p> This is just displaying the initial array, not the updated.
It took a while to debug but the problem was in scope. this.values = arr; console.log(this.values); This worked OK in the scope of the function, but this wasn't referring to the array I was thinking of. Needed to add const self = this; on global level. It was hard to notice that but works OK now.l

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.