vue3 props传递ref([]) 并且使用
时间: 2023-12-10 10:38:01 浏览: 43
在 Vue 3 中,可以使用 `setup` 函数来定义组件,并通过 `props` 接收父组件传递的数据。如果要将一个数组作为 `props` 传递给子组件,并在子组件中使用该数组的引用,可以使用 `ref` 来创建一个响应式的引用。
下面是一个示例代码:
```html
<!-- ParentComponent.vue -->
<template>
<div>
<child-component :my-array="myArray"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
components: {
ChildComponent
},
setup() {
const myArray = Vue.ref([1, 2, 3])
return {
myArray
}
}
}
</script>
```
```html
<!-- ChildComponent.vue -->
<template>
<div>
<ul>
<li v-for="item in myArray" :key="item">{{ item }}</li>
</ul>
<button @click="addItem">Add Item</button>
</div>
</template>
<script>
import { defineProps } from 'vue'
export default {
props: {
myArray: {
type: Array,
required: true
}
},
setup(props) {
const addItem = () => {
props.myArray.push(props.myArray.length + 1)
}
return {
addItem
}
}
}
</script>
```
在上面的代码中,父组件 `ParentComponent` 通过 `props` 将 `myArray` 数组传递给子组件 `ChildComponent`。在子组件中,我们使用 `defineProps` 来定义 `myArray` 的类型和必要性,然后在 `setup` 函数中使用 `props` 对象来获取该数组的引用,并添加了一个 `addItem` 方法,以便在点击按钮时向数组中添加一个新项。
请注意,由于我们使用了 `ref` 来创建 `myArray` 的响应式引用,因此在子组件中添加或删除项时,父组件中的 `myArray` 数组也会相应地更新。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)