Vue3 setup 语法中的组件间通用通信方式

张开发
2026/4/16 23:01:58 15 分钟阅读

分享文章

Vue3 setup 语法中的组件间通用通信方式
1. 父传子方式一defineProps 或 $attrs实现步骤在父组件中通过为子组件添加属性的方式传递属性数据在子组件中通过defineProps接收父组件传递的属性// 父组件 template div child :user-infouserInfo / /div /template script setup import child from ./components/child.vue const userInfo { name: 张三, age: 24 } /script// 子组件child template div h2我是child组件/h2 /div /template script setup defineProps({ userInfo: { type: Object, default: () ({}) } }) /script方式二provide/inject详见官方文档依赖注入2. 子传父实现步骤在子组件上通过emit触发父组件中当前子组件上的自定义事件在父组件的子组件上添加该自定义事件并设置相应的处理函数// 父组件 template div // 1.处理子组件的自定义事件update-user-info child update-user-infoupdateUserInfo / /div /template script setup import { ref } from vue import child from ./components/child.vue const userInfo ref({ name: 张三, age: 24 }) // 2.子组件的自定义事件update-user-info的处理函数接受传递的参数newUserInfo const updateUserInfo (newUserInfo) { userInfo.value newUserInfo } /script// 子组件child template div h2我是child组件/h2 button clickhandleChangeUserInfoCLick修改父组件的userInfo/button /div /template script setup const newUserInfo { name: 李四, age: 30, height: 1.88 } // 1.自定义事件和获取自定义事件对象 const emit defineEmits([update-user-info]) const handleChangeUserInfoCLick () { // 2.触发父组件中当前组件上的自定义事件update-user-info同时传递数据newUserInfo emit(update-user-info, newUserInfo) } /script3. 同层级的组件间通信方式1子传父父调用另一个子组件的方法实现步骤第一个子组件先传递数据给父组件然后父组件通过ref传递给另一个子组件在子组件child上通过emit触发父组件中当前子组件child上的自定义事件在父组件的子组件child上添加该自定义事件并设置相应的处理函数在子组件child-brother上暴露相应的处理方法在父组件中获取子组件child-brother的ref然后通过ref对象引用子组件上的方法并传递参数。下面案例实现的功能子组件child发送更新后的 newUserInfo 数据给其父组件和其兄弟组件child-brother父组件及其兄弟组件接受数据并进行相应的逻辑处理。// 父组件 template div // 1.处理子组件的自定义事件update-user-info child update-user-infoupdateUserInfo / child-brother refbrotherRef / /div /template script setup import { ref } from vue import child from ./components/child.vue let userInfo { name: 张三, age: 24 } // 2.子组件的自定义事件update-user-info的处理函数接受传递的参数newUserInfo const brotherRef ref() const updateUserInfo (newUserInfo) { userInfo newUserInfo brotherRef.value.receiveNewUserInfo(newUserInfo) } /script// 子组件child template div h2我是child组件/h2 button clickhandleChangeUserInfoCLick修改父组件的userInfo/button /div /template script setup const newUserInfo { name: 李四, age: 30, height: 1.88 } // 1.自定义事件和获取自定义事件对象 const emit defineEmits([update-user-info]) const handleChangeUserInfoCLick () { // 2.触发父组件中当前组件上的自定义事件update-user-info同时传递数据newUserInfo emit(update-user-info, newUserInfo) } /script// 子组件child-brother template div h2我是child-brother组件/h2 /div /template script setup const userInfo {} const receiveNewUserInfo (newUserInfo) { userInfo newUserInfo } defineExpose({ receiveNewUserInfo }) /script方式2事件总线常用 npm 库mitt

更多文章