组件通信-provide、inject
-
概述:实现祖孙组件直接通信
-
具体使用:
-
在祖先组件中通过
provide
配置向后代组件提供数据 -
在后代组件中通过
inject
配置来声明接收数据
-
-
具体编码:
【第一步】父组件中,使用
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>