前端|Vue Vue3 超详细 实现组件通信: 父子、子父及兄弟组件间的数据流转
warning:
这篇文章距离上次修改已过184天,其中的内容可能已经有所变动。
<template>
<div>
<!-- 父组件通过属性传递数据给子组件 -->
<ChildComponent :parentData="parentData" />
</div>
</template>
<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
setup() {
// 父组件的数据
const parentData = ref('父组件数据');
// 返回需要在模板中使用的响应式数据
return {
parentData
};
}
};
</script>
子组件:
<template>
<div>
{{ parentData }}
</div>
</template>
<script>
import { defineComponent, toRefs } from 'vue';
export default defineComponent({
props: {
// 声明接受父组件传递的数据
parentData: {
type: String,
default: ''
}
},
setup(props) {
// 使用toRefs确保props是响应式的
const { parentData } = toRefs(props);
return {
parentData
};
}
});
</script>
这个例子展示了如何在Vue 3中实现父子组件间的通信。父组件通过属性传递数据给子组件,子组件通过props接收数据。使用toRefs
确保props是响应式的,这样可以在子组件内部保持响应性。
评论已关闭