vue3怎么用ref和push向数组添加对象
时间: 2024-02-12 14:04:46 浏览: 412
在 Vue 3 中,可以使用 ref
和 push
方法向数组中添加对象,方法如下:
<template>
<div>
<button @click="addObject">Add Object</button>
<ul>
<li v-for="item in myArray" :key="item.id">{{ item.name }}</li>
</ul>
</div>
</template>
<script>
import { ref } from "vue";
export default {
setup() {
const myArray = ref([]);
const addObject = () => {
// 使用 ref 定义空对象
const newObject = {};
newObject.id = myArray.value.length + 1;
newObject.name = "Object " + newObject.id;
// 使用 push 方法向数组中添加对象
myArray.value.push(newObject);
};
return {
myArray,
addObject
};
}
};
</script>
在上面的例子中,我们首先通过 ref
定义了一个空数组 myArray
,然后在 addObject
方法中定义了一个新的对象,并将其添加到数组中。需要注意的是,在 Vue 3 中,需要使用 ref.value
来访问 ref
定义的值。另外,在 setup()
函数中返回的对象中,需要将定义的变量和方法返回。
相关推荐


















