vue3父子组件传对象,子组件访问修改父组件对象中的属性值
在Vue 3中,父子组件之间的数据传输通常通过props和emit进行。父组件可以通过props向下传递数据给子组件,子组件则可以通过emit向上通知父组件更新数据。如果需要在子组件中修改父组件对象中的属性值,可以使用一个名为ref的Vue 3新特性。
以下是一个示例,演示了如何在Vue 3中实现父子组件之间的对象传递和属性修改:
父组件:
<template>
<div>
<h2>父组件</h2>
<p>姓名:{{ person.name }}</p>
<p>年龄:{{ person.age }}</p>
<button @click="increaseAge">增加年龄</button>
<hr>
<child-component :person="person" @update:person="updatePerson"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
person: {
name: '张三',
age: 25
}
};
},
methods: {
increaseAge() {
this.person.age++;
},
updatePerson(newPerson) {
this.person = newPerson;
}
}
};
</script>
子组件:
<template>
<div>
<h3>子组件</h3>
<p>姓名:{{ person.name }}</p>
<p>年龄:{{ person.age }}</p>
<button @click="increaseAge">增加年龄</button>
</div>
</template>
<script>
export default {
props: {
person: {
type: Object,
required: true
}
},
methods: {
increaseAge() {
this.$emit('update:person', { ...this.person, age: this.person.age + 1 });
}
}
};
</script>
在这个示例中,父组件中有一个名为person的对象,包含name和age两个属性。父组件通过props将person对象传递给子组件。子组件中有一个按钮,当点击该按钮时,会触发一个名为increaseAge的方法。在increaseAge方法中,我们使用this.$emit向上发送一个事件,并传递一个新的person对象,其中age属性值加1。父组件中监听这个事件,并在事件处理函数updatePerson中更新person对象的属性值。这样,子组件就能够修改父组件对象中的属性值。