《Vue3 Composition API 实战:父子组件通信的新方式与案例解析》
·
在Vue3的Composition API中,父子组件通信通过更灵活的响应式API实现。以下是核心方法与完整案例:
一、父子通信新方式
-
父传子:
defineProps
替代Vue2的props选项,支持TS类型推导:<!-- 子组件 Child.vue --> <script setup> const props = defineProps({ title: { type: String, required: true }, count: Number }) </script> <template> <h3>{{ title }}</h3> <p>计数: {{ count }}</p> </template> -
子传父:
defineEmits
声明自定义事件并触发:<!-- 子组件 Child.vue --> <script setup> const emit = defineEmits(['updateCount']) const handleClick = () => { emit('updateCount', 10) // 传递参数 } </script> <template> <button @click="handleClick">增加</button> </template> -
父调子方法:
defineExpose + ref
暴露子组件方法供父组件调用:<!-- 子组件 Child.vue --> <script setup> const reset = () => { /* 重置逻辑 */ } defineExpose({ reset }) // 暴露方法 </script> <!-- 父组件 Parent.vue --> <script setup> import { ref } from 'vue' const childRef = ref(null) const callChildMethod = () => { childRef.value?.reset() // 安全调用 } </script> <template> <Child ref="childRef" /> <button @click="callChildMethod">触发子组件重置</button> </template>
二、实战案例:表单验证组件
场景需求
- 父组件:提交表单时触发子组件验证
- 子组件:返回验证结果
代码实现
<!-- 子组件 FormValidator.vue -->
<script setup>
import { ref } from 'vue'
const isValid = ref(false)
const validate = () => {
isValid.value = /* 验证逻辑 */
return isValid.value
}
defineExpose({ validate }) // 暴露验证方法
</script>
<!-- 父组件 FormContainer.vue -->
<script setup>
import { ref } from 'vue'
import FormValidator from './FormValidator.vue'
const validatorRef = ref(null)
const submitForm = async () => {
if (await validatorRef.value?.validate()) {
alert('验证通过,提交成功!')
} else {
alert('验证失败!')
}
}
</script>
<template>
<FormValidator ref="validatorRef" />
<button @click="submitForm">提交表单</button>
</template>
三、对比Vue2的优势
- 类型安全
defineProps/defineEmits提供自动类型推导 - 代码组织
逻辑关注点集中,避免在options中跳跃查找 - 灵活性
通过ref+defineExpose实现方法级精确控制 - TS支持
完整类型提示(需配合<script setup lang="ts">)
最佳实践建议:
- 简单数据流优先使用
props/emit- 复杂交互场景使用
ref+defineExpose- 跨层级通信推荐
provide/inject- 使用
v-model实现双向绑定时,Vue3支持多个v-model绑定(如v-model:title)
通过组合式API,父子通信从"配置驱动"转向"函数驱动",大幅提升代码可维护性和复用性。
更多推荐
所有评论(0)