组件间通信
Props 父传子
基本用法
Vue
<!-- 父组件-->
<template>
<ChildComponent :message="parentMessage" />
</template>
<script setup>
import ChildComponent from './ChildComponent.vue'
const parentMessage = 'Hello from Parent'
</script>
Vue
<!-- 子组件-->
<template>
<div>{{ message }}</div>
</template>
<script setup>
defineProps({
message: {
type: String,
required: true
}
})
</script>
emit 子传父
基本用法
Vue
<!-- 子组件-->
<template>
<button @click="sendMessage">发送消息</button>
</template>
<script setup>
const emit = defineEmits(['messageSent'])
function sendMessage() {
emit('messageSent', 'Hello from Child')
}
</script>
Vue
<!-- 父组件-->
<template>
<ChildComponent @message-sent="handleMessage" />
</template>
<script setup>
import ChildComponent from './ChildComponent.vue'
function handleMessage(msg) {
console.log('收到子组件消息:', msg)
}
</script>
v-model 双向绑定
基本用法
Vue
<template>
<ChildComponent v-model="count" /> <!-- 双向绑定count变量 -->
<div>父组件值: {{ count }}</div> <!-- 显示当前值 -->
</template>
<script setup>
import { ref } from 'vue'
import ChildComponent from './ChildComponent.vue'
const count = ref(0) // 创建响应式数据
</script>
Vue
<template>
<button @click="updateValue">增加</button> <!-- 触发更新 -->
</template>
<script setup>
const props = defineProps(['modelValue']) // 接收父组件传递的值
const emit = defineEmits(['update:modelValue']) // 声明要触发的事件
function updateValue() {
// 发出事件通知父组件更新,携带新值
emit('update:modelValue', props.modelValue + 1)
}
</script>
Provide/Inject 跨层级通信
基本用法
Vue
<template>
<ParentComponent />
</template>
<script setup>
import { provide, ref } from 'vue'
import ParentComponent from './ParentComponent.vue'
const count = ref(0)
provide('globalCount', count)
</script>
Vue
<template>
<div>注入的值: {{ count }}</div>
</template>
<script setup>
import { inject } from 'vue'
const count = inject('globalCount')
</script>
通信方式对比
方式 | 方向 | 适用场景 | 优点 | 缺点 | 复杂度 |
---|---|---|---|---|---|
Props | 父传子 | 父组件向子组件传递数据 | 简单直观,类型安全 | 只能单向传递 | ⭐ |
Emit | 子传父 | 子组件向父组件传递数据 | 解耦父子组件 | 需要手动定义事件 | ⭐⭐ |
v-model | 双向绑定 | 表单类组件双向绑定 | 语法简洁,标准化 | 仅适用于简单场景 | ⭐⭐ |
Provide/Inject | 任意 | 跨层级组件通信 | 避免逐层传递 | 不利于组件复用 | ⭐⭐⭐ |