在 Vue 3 中,通过 props 传递数据,可以让子组件接收父组件的数据。 但 props 本身是单向数据流,只能从父组件传递给子组件,不能直接从子组件修改父组件的数据。
为了实现父子组件数据互通,可以使用事件(event)通信或者 ref
和 reactive
下面分别介绍这两种方法。
1. 事件通信:
子组件可以使用 $emit
方法触发一个自定义事件,将子组件的数据传递给父组件。父组件通过监听该事件并处理来实现数据互通。
父组件:
<template>
<div>
<child-component :dataFromParent="parentData" @updateParentData="updateData($event)"></child-component>
</div>
</template>
<script>
import ChildComponent from '@/components/ChildComponent.vue';
export default {
components: {
ChildComponent,
},
data() {
return {
parentData: 'This is data from parent component',
};
},
methods: {
updateData(newValue) {
this.parentData = newValue;
},
},
};
</script>
子组件:
<template>
<div>
<p>{{ dataFromParent }}</p>
<button @click="changeParentData">Change Parent Data</button>
</div>
</template>
<script>
export default {
props: {
dataFromParent: String,
},
methods: {
changeParentData() {
this.$emit('updateParentData', 'New data from child component');
},
},
};
</script>
2. 使用 ref
和 reactive
:
通过创建一个响应式对象,将其作为子组件的 prop 传递,这样父子组件可以共享数据。
父组件:
<template>
<div>
<child-component :sharedData="sharedData" />
<p>{{ sharedData.value }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from '@/components/ChildComponent.vue';
const sharedData = ref('This is data from parent component');
</script>
子组件:
<template>
<div>
<p>{{ sharedData.value }}</p>
<button @click="changeSharedData">Change Shared Data</button>
</div>
</template>
<script setup>
import { defineProps } from 'vue';
const props = defineProps({
sharedData: Object,
});
const changeSharedData = () => {
props.sharedData.value = 'New data from child component';
};
</script>
通过以上两种方法,可以实现 Vue 3 中父子组件数据的互通