Vue 组件通信三要素:Props、Emit、Refs
1. Props(父 → 子)
父组件通过自定义属性向子组件传递数据。
子组件使用props数组(或对象)声明接收的属性名,父组件在模板中像 HTML 属性一样赋值。
vue
<!-- 父组件 --> <Child :msg="parentMsg" /> <!-- 子组件 --> <script> export default { props: ['msg'] // 或对象形式带类型校验 } </script>2. Emit(子 → 父)
子组件通过$emit触发自定义事件,并携带参数。
父组件使用@eventName或v-on:eventName监听,触发后执行自身方法,并接收子组件传来的参数。
vue
<!-- 子组件 --> <button @click="$emit('update', value)">触发</button> <!-- 父组件 --> <Child @update="handleUpdate" />这种模式与EventEmitter的事件驱动机制类似,属于发布-订阅思想。
3. Refs(父直接调用子)
父组件通过ref属性给子组件起名,然后通过this.$refs.xxx获取子组件实例,从而直接调用子组件的方法或读取其属性,并可传递参数。
vue
<!-- 父组件 --> <Child ref="childRef" /> <button @click="callChildMethod">调用</button> <script> export default { methods: { callChildMethod() { this.$refs.childRef.doSomething('param') console.log(this.$refs.childRef.someData) } } } </script>补充:Vue 3 中的变化
组合式 API中使用
defineProps和defineEmits声明,更类型友好。vue
<script setup> const props = defineProps({ msg: String }) const emit = defineEmits(['update']) emit('update', 'newValue') </script>v-model本质上就是props+emit的语法糖(默认modelValue属性和update:modelValue事件)。
总结
| 方式 | 方向 | 用途 |
|---|---|---|
| Props | 父 → 子 | 传递数据 |
| Emit | 子 → 父 | 触发事件、传递参数 |
| Refs | 父 → 子 | 直接调用子组件方法/属性(打破单向流,谨慎使用) |
合理搭配这三种方式,即可轻松应对 Vue 中绝大部分组件通信场景。