Skip to content

组件间通信

约 542 字大约 2 分钟

前端开发组件传参

2025-06-22

Props 父传子

基本用法

Vue
<!-- 父组件-->
<template>
  <ChildComponent :message="parentMessage" />
</template>

<script setup>
import ChildComponent from './ChildComponent.vue'
const parentMessage = 'Hello from Parent'
</script>

emit 子传父

基本用法

Vue
<!-- 子组件-->
<template>
  <button @click="sendMessage">发送消息</button>
</template>

<script setup>
const emit = defineEmits(['messageSent'])

function sendMessage() {
  emit('messageSent', 'Hello from Child')
}
</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>

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>

通信方式对比

方式方向适用场景优点缺点复杂度
Props父传子父组件向子组件传递数据简单直观,类型安全只能单向传递
Emit子传父子组件向父组件传递数据解耦父子组件需要手动定义事件⭐⭐
v-model双向绑定表单类组件双向绑定语法简洁,标准化仅适用于简单场景⭐⭐
Provide/Inject任意跨层级组件通信避免逐层传递不利于组件复用⭐⭐⭐