panthro
panthro

Reputation: 24099

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

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?

Upvotes: 20

Views: 50598

Answers (1)

Dan
Dan

Reputation: 63139

It depends how you define the array

Using reactive:

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

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

Using ref:

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

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

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.

Upvotes: 47

Related Questions