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

Viewed 16555

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?

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.

Related