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

10,782

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.

Share:
10,782
panthro
Author by

panthro

Updated on June 12, 2022

Comments

  • panthro
    panthro almost 2 years

    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?

    • Parzh from Ukraine
      Parzh from Ukraine almost 3 years
      That snippet doesn’t look like valid JavaScript code. What’s ['a' => 'b'] supposed to mean?
  • Haad Nadeem
    Haad Nadeem over 2 years
    What if the array was in an object like const a = ref({c:[]}), how would we push something into c ?
  • Dan
    Dan over 2 years
    @HaadNadeem Don't use ref on an object. const a = reactive({ c: [] }); a.c.push(1) jsfiddle.net/sh0ber/0xoep5t9