使用场景:有一个父组件,里头有子组件,有孙组件,有很多后代组件,共享父组件数据。
父组件:
<template>
<div>
父组件--count: {{ count }}
</div>
<div>
<br>
<br>
<hr>
<inject-son-vue></inject-son-vue>
</div>
</template>
<script>
import { provide,ref } from 'vue'
import InjectSonVue from './InjectSon.vue'
export default {
components:{
InjectSonVue
},
setup() {
const count = ref(10)
provide("count",count)
const updateCount = () => {
count.value = 999
}
provide("updateCount",updateCount)
return {
count
}
}
}
</script>
<style scoped>
</style>
子组件:
<template>
<div>
子组件--count:{{ count }}
</div>
<div>
<br>
<br>
<hr>
<inject-grand-son-vue></inject-grand-son-vue>
</div>
</template>
<script>
import { inject } from 'vue'
import InjectGrandSonVue from './InjectGrandSon.vue'
export default {
components:{
InjectGrandSonVue
},
setup() {
const count = inject("count")
return {
count
}
}
}
</script>
<style scoped>
</style>
后代组件:
<template>
<div>
孙组件--count: {{ count }}
</div>
<br>
<br>
<br>
<button @click="updateCount">
更改
</button>
</template>
<script>
import { inject } from 'vue'
export default {
setup() {
const count = inject("count")
const updateCount = inject("updateCount")
return {
count,
updateCount
}
}
}
</script>
<style scoped>
</style>
总结:
-
provide函数提供数据和函数给后代组件使用
-
inject函数给当前组件注入provide提供的数据和函数