20

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
  • 4
    That snippet doesn’t look like valid JavaScript code. What’s ['a' => 'b'] supposed to mean? Commented Jun 3, 2021 at 22:58

1 Answer 1

47

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.

Sign up to request clarification or add additional context in comments.

2 Comments

What if the array was in an object like const a = ref({c:[]}), how would we push something into c ?
@HaadNadeem a.value.c.push(1). Since a is a ref, you use value. Since c is not a ref, you don't.

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.