应用场景:
祖先级别的组件的数据有很多子组件要用的时候,可以使用依赖注入(provide&inject)的方法传递数据,这样就无需使用多次父传子的形式去传递数据,避免页面过度冗余。
基本使用
祖先组件App.vue
<template>
<div>
<button @click="btn">祖先修改</button>
<Father></Father>
</div>
</template>
<script setup lang="ts">
import { ref, provide, readonly } from 'vue';
import Father from './components/father.vue'
const colorValue = ref('red')
// 将数据定义为readonly后子组件不能修改provide的值,当前组件仍可以修改
// 提供出去
provide('color', readonly(colorValue))
const btn = () => {
colorValue.value = 'blue'
}
</script>
<style scoped lang="less">
</style>
父组件Father.vue
<template>
<div>
<div class="divBgc">
我是父组件
<Son></Son>
</div>
</div>
</template>
<script setup lang="ts" name="Father">
import { inject, Ref } from 'vue'
import Son from '../components/son.vue'
const color = inject<Ref<string>>('color')
</script>
<style scoped lang="less">
.divBgc {
width: 500px;
height: 500px;
background-color: v-bind(color);
}
</style>
子组件Son.vue
<template>
<div>
<div class="divBgc">我是子组件</div>
<button @click="btn">子组件修改</button>
</div>
</template>
<script setup lang="ts" name="Son">
import { Ref, inject } from 'vue';
// 注入进来
const colorValue = inject<Ref<string>>('color')
const btn = () => {
// 非空断言
colorValue!.value = 'skyblue'
}
</script>
<style scoped lang="less">
.divBgc {
width: 200px;
height: 200px;
background-color: v-bind(colorValue);
}
</style>