vue3 父子组件循环传参
时间: 2025-01-01 14:36:20 浏览: 38
Vue3 中父子组件之间的数据传递通常有两种常见的方法:props 和自定义事件(emits)。如果你需要从父组件循环地向子组件传递参数,可以使用数组或者对象的方式。
**1. Props (props-in)**
这是最常见的方式,父组件通过props向下传递数据。假设你在父组件有一个数组:
```html
<template>
<div v-for="(item, index) in parentArray">
<child-component :prop="item" :index="index"></child-component>
</div>
</template>
<script setup>
import ChildComponent from './ChildComponent.vue';
const parentArray = ['value1', 'value2', 'value3'];
</script>
```
然后在子组件接收并显示这个值:
```vue
<template>
<p>Parent data: {{ prop }}</p>
</template>
<script>
export default {
props: {
prop: String,
// 如果需要传递其他额外信息,如索引
index: Number
}
};
</script>
```
**2. 自定义事件 (emits)**
如果数据需要双向绑定或者动态更新,你可以考虑使用自定义事件:
```html
<template>
<div v-for="(item, index) in parentArray">
<child-component @update-child-data="handleUpdateData(index, item)" :data="item"></child-component>
</div>
</template>
<script setup>
import ChildComponent from './ChildComponent.vue';
const parentArray = ['value1', 'value2', 'value3'];
function handleUpdateData(index, newValue) {
setParentArray(index, newValue);
}
</script>
```
在子组件内触发事件,传递新值:
```vue
<template>
<button @click="updateData">Update Data</button>
</template>
<script>
export default {
methods: {
updateData() {
this.$emit('update-child-data', this.data); // 或者修改后的数据
}
},
props: {
data: String
}
};
</script>
```
阅读全文
相关推荐


















