0

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?

4
  • See Array.prototype.concat() and Reactivity in depth on Vue docs. Commented Sep 8, 2017 at 21:22
  • I tried using concat() to merge the arrays but it wouldn't update the view where I was rendering them. I also tried Vue.set() but also couldn't get it to work, that's why I had to resort back to the for loop. @Nit Commented Sep 8, 2017 at 21:26
  • How were you using concat? Commented Sep 9, 2017 at 1:48
  • I was just doing this: this.existingArray.concat(response.data). Thanks everyone, I got it working with concat now and it's much easier than the for loop. Commented Sep 9, 2017 at 1:51

1 Answer 1

2

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.

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.