Brian Moreno
Brian Moreno

Reputation: 1027

Update v-for When Data Is Added To Array - VueJS

I'm kinda new to VueJS so I was hoping to get some help. I'm currently returning an array of json objects from a PHP file.

Example:

<?php
  /*
   Returns an array similar to this:
    [
      {name: 'foo'}, 
      {name: 'bar'}, 
      {name: 'banana'}
    ]
  */

  echo json_encode(array_values($array));
?>

And I'm appending this array of objects to an already existing array of objects in Vue:

axios.post('http://localhost/get_array.php').then(response => {
  // Append returned array to already existing array
  for (var i = 0; i <= response.data.length - 1; i++) {
    this.existingArray.push(response.data[i])
  }
}).catch(e => {
  console.log("Error")
})

Right now I'm appending the data with a for loop but I was wondering if VueJS has an in-built function that does this automatically without having to use the for loop?

Upvotes: 0

Views: 1233

Answers (1)

Steve Holgado
Steve Holgado

Reputation: 12089

You can use concat which returns a new concatenated array:

axios.post('http://localhost/get_array.php')
  .then(response => {
    this.existingArray = this.existingArray.concat(response.data)
  })
  .catch(e => {
    console.log("Error")
  })

Updating existingArray with the result of calling concat with the response data should trigger the update.

Upvotes: 2

Related Questions