vue如何实现父子通信
父子组件通信方法
Vue 中父子组件通信主要通过 props 和自定义事件实现,以下是具体方法:
props 传递数据
父组件通过 props 向子组件传递数据:
<!-- 父组件 -->
<template>
<ChildComponent :message="parentMessage" />
</template>
<script>
export default {
data() {
return {
parentMessage: 'Hello from parent'
}
}
}
</script>
<!-- 子组件 -->
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
props: {
message: String
}
}
</script>
自定义事件通信
子组件通过 $emit 触发事件,父组件监听事件:

<!-- 子组件 -->
<template>
<button @click="sendMessage">Send</button>
</template>
<script>
export default {
methods: {
sendMessage() {
this.$emit('message-from-child', 'Hello from child')
}
}
}
</script>
<!-- 父组件 -->
<template>
<ChildComponent @message-from-child="handleMessage" />
</template>
<script>
export default {
methods: {
handleMessage(msg) {
console.log(msg) // 输出: Hello from child
}
}
}
</script>
v-model 双向绑定
实现父子组件双向数据绑定:
<!-- 父组件 -->
<template>
<ChildComponent v-model="parentValue" />
</template>
<script>
export default {
data() {
return {
parentValue: ''
}
}
}
</script>
<!-- 子组件 -->
<template>
<input :value="value" @input="$emit('input', $event.target.value)" />
</template>
<script>
export default {
props: ['value']
}
</script>
$refs 访问子组件

父组件通过 ref 直接访问子组件实例:
<!-- 父组件 -->
<template>
<ChildComponent ref="child" />
<button @click="callChildMethod">Call Child Method</button>
</template>
<script>
export default {
methods: {
callChildMethod() {
this.$refs.child.childMethod()
}
}
}
</script>
<!-- 子组件 -->
<script>
export default {
methods: {
childMethod() {
console.log('Child method called')
}
}
}
</script>
provide/inject 跨级通信
祖先组件通过 provide 提供数据,后代组件通过 inject 注入:
<!-- 祖先组件 -->
<script>
export default {
provide() {
return {
theme: 'dark'
}
}
}
</script>
<!-- 后代组件 -->
<script>
export default {
inject: ['theme'],
created() {
console.log(this.theme) // 输出: dark
}
}
</script>
注意事项
- props 是单向数据流,子组件不应直接修改 props
- 自定义事件名推荐使用 kebab-case
- $refs 只在组件渲染完成后才可访问
- provide/inject 主要用于深层嵌套组件通信






