欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 文化 > 组件通信-provide、inject

组件通信-provide、inject

2025/5/3 7:40:58 来源:https://blog.csdn.net/karlaofsky/article/details/147672251  浏览:    关键词:组件通信-provide、inject
  1. 概述:实现祖孙组件直接通信

  2. 具体使用:

    • 在祖先组件中通过provide配置向后代组件提供数据

    • 在后代组件中通过inject配置来声明接收数据

  3. 具体编码:

    【第一步】父组件中,使用provide提供数据

父组件:

<template><div class="father"><h3>父组件</h3><h4>资产:{{ money }}</h4><h4>{{ car.brand }}价值:{{ car.price }}</h4><button @click="money += 1">资产+1</button><button @click="car.price += 1">汽车价格+1</button><Child /></div>
</template><script setup lang="ts" name="Father">
import Child from './Child.vue'
import { ref, reactive, provide } from "vue";
// 数据
let money = ref(100)
let car = reactive({brand: '奔驰',price: 100
})
// 用于更新money的方法
function updateMoney(value: number) {money.value -= value
}
// 提供数据
provide('moneyContext', { money, updateMoney })
provide('car', car)
</script>
<style scoped>
.father {background-color: pink;width: 200px;height: 400px;padding: 20px;
}button {margin: 5px 0;
}
</style>

 子组件:注意:子组件中不用编写任何东西,是不受到任何打扰的

<template><div class="child"><h3>子组件</h3><GrandChild /></div>
</template><script setup lang="ts" name="Child2">
import GrandChild from './GrandChild.vue'
</script>
<style scoped>
.child {background-color: aquamarine;height: 190px;padding: 5px;
}
</style>

孙组件:【第二步】孙组件中使用inject配置项接受数据。

<template><div class="grand-child"><h3>我是孙组件</h3><h4>资产:{{ money }}</h4><h4>{{ car.brand }}价值:{{ car.price }}</h4><button @click="updateMoney(6)">点我花爷爷的钱</button></div>
</template><script setup lang="ts" name="GrandChild">
import { inject } from 'vue';
// 注入数据(解构赋值) 默认值:{ money: 0, updateMoney: (param: number) => { } }
let { money, updateMoney } = inject('moneyContext', { money: 0, updateMoney: (param: number) => { } })
//注入数据 默认值:{ brand: '未知', price: 0 }
let car = inject('car', { brand: '未知', price: 0 })
</script>
<style scoped>
.grand-child {background-color: rgb(173, 148, 232);height: 120px;margin: 10px 0;
}
</style>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词