前段时间写过一个 vue3的父子组件传参,经过一段时间的学习,现在进行补充一些
废话不多说:
1. 使用 props
和 emits
这是 Vue 2 中就存在的父子通信方式,在 Vue 3 中依然适用。父组件通过 props
向子组件传递数据,子组件通过 emits
触发事件来通知父组件。
子组件:
<template>
<button @click="handleClick">点击我</button>
</template>
<script>
export default {
props: { message: String },
emits: ['custom-event'],
methods: {
handleClick() { // 触发事件并传递数据
this.$emit('custom-event', '来自子组件的消息');
}
}
}
</script>
父组件:
<template>
<child-component :message="parentMessage" @custom-event="handleEvent"></child-component> </template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: { ChildComponent },
data() {
return {
parentMessage: 'Hello Child'
};
},
methods: {
handleEvent(data) {
console.log(data); // 输出:来自子组件的消息
}
}
} </script>
2. 使用 provide
/ inject
这是 Vue 提供的另一种父子通信方式,适用于更深层次的组件通信。provide
在父组件中定义,inject
在任何子孙组件中使用。
父组件:
<script>
export default {
provide() {
return {
message: 'Hello from Parent'
};
}
}
</script>
子孙组件:
<script>
export default {
inject: ['message']
}
</script>
3. 使用 ref
和 reactive
在 Vue 3 中,你还可以使用 ref
或 reactive
创建响应式引用或对象,并在父子组件之间共享。
父组件:
<template>
<child-component :sharedState="sharedStateRef" />
</template>
<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
setup() {
const sharedStateRef = ref({
message: 'Hello from Parent'
});
return {
sharedStateRef
};
}
}
</script>
子组件:
<script>
import { toRefs } from 'vue';
export default {
props: {
sharedStateRef: {
type: Object,
default: () => ({})
}
},
setup(props) {
const { message } = toRefs(props.sharedStateRef);
return {
message
};
}
}
</script>
4. 使用事件总线或状态管理
对于更复杂的应用,你可能需要使用事件总线(Event Bus)或状态管理库(如 Vuex)来实现组件间的通信。这些方法适用于跨层级或非直接父子关系的组件通信。
5. 使用 provide
/ inject
的高级用法
Vue 3 还提供了 provide
/ inject
的高级用法,允许你传递响应式引用(ref
)或响应式对象(reactive
)。
父组件:
<script>
import { reactive } from 'vue';
export default {
setup() {
const state = reactive({
message: 'Hello from Parent'
});
return {
state
};
}
}
</script>
子孙组件:
<script>
import { inject } from 'vue';
export default {
setup() {
const state = inject('state');
return {
message: state.message
};
}
}
</script>