【问题标题】:How can I push to an array (in Vue 3)?如何推送到数组(在 Vue 3 中)?
【发布时间】:2021-03-11 15:00:45
【问题描述】:

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

this.myArray.push(['a' => 'b']);

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

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

【问题讨论】:

  • 那个 sn-p 看起来不像是有效的 JavaScript 代码。 ['a' => 'b'] 应该是什么意思?

标签: vue.js vuejs3


【解决方案1】:

这取决于你如何定义数组

使用ref:

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

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

使用reactive:

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

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

其他问题:

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

myArray.push({ a: 'b' });

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

【讨论】:

  • 如果数组在一个像 const a = ref({c:[]}) 这样的对象中,我们如何将一些东西压入 c 中?
  • @HaadNadeem 不要在对象上使用ref。 const a = reactive({ c: [] }); a.c.push(1)jsfiddle.net/sh0ber/0xoep5t9
猜你喜欢
  • 2022-01-22
  • 1970-01-01
  • 2022-11-02
  • 2022-08-23
  • 2020-07-26
  • 1970-01-01
  • 2018-03-06
  • 1970-01-01
  • 2019-08-04
相关资源
最近更新 更多