如何推送到数组(在 Vue 3 中)?

pan*_*hro 2 vue.js vuejs3

我有一个数组,我想向它推送一些数据。

this.myArray.push(['a' => 'b']);
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不适用于 Vue 3,因为它myArray似乎包装在代理对象中。

有谁知道如何在 Vue 3 中推送到数组?

Dan*_*Dan 6

这取决于你如何定义数组

使用ref

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

myArray.value.push(4); // With a `ref` you need to use `value` 
Run Code Online (Sandbox Code Playgroud)

使用reactive

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

myArray.push(4); // push works as normal
Run Code Online (Sandbox Code Playgroud)

其他事宜:

您的语法对于推送的内容不正确,也许您想要:

myArray.push({ a: 'b' });
Run Code Online (Sandbox Code Playgroud)

另外,请记住this,Vue 3 组合 API 中没有组件访问权限。