Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I push to an array (in Vue 3)?

Tags:

vue.js

vuejs3

I have an array and I would like to push some data to it.

this.myArray.push(['a' => 'b']);

Unfortunately this does not work with Vue 3 as myArray appears to be wrapped in a proxy object.

Does anyone know how to push to an array in Vue 3?

like image 608
panthro Avatar asked Nov 29 '20 13:11

panthro


People also ask

How do I push data into an array in Vue?

To push items into an array in the data object in Vue. js, we can make a copy of the object to append to the array before we call push with it. to call this.

How do you push an object to an array of arrays?

To push an object into an array, call the push() method, passing it the object as a parameter. For example, arr. push({name: 'Tom'}) pushes the object into the array. The push method adds one or more elements to the end of the array.

How do you push in Vue?

With Vue Router, you can use its router. push() function to programmatically navigate between routes on your site. You can either call push() with a string path, or with an object containing either the path or name of the route.

How do you push a new item into an array?

JavaScript Array push() The push() method adds new items to the end of an array. The push() method changes the length of the array. The push() method returns the new length.


Video Answer


1 Answers

It depends how you define the array

Using ref:

const myArray = ref([1,2,3]);

myArray.value.push(4); // With a `ref` you need to use `value` 

Using reactive:

const myArray = reactive([1,2,3])

myArray.push(4); // push works as normal

Other issues:

Your syntax is incorrect for what's being pushed, maybe you want:

myArray.push({ a: 'b' });

Also, keep in mind there is no component this access in the Vue 3 composition API.

like image 77
Dan Avatar answered Oct 16 '22 14:10

Dan