一、基本用法:
//父组件
import { ref, provide } from 'vue'
const radio = ref<string>('red')
provide('myColor',radio) //注入依赖
//儿子组件、孙子组件、曾孙子组件
import { inject, ref } from 'vue'
import type { Ref } from 'vue';
const myColor = inject<Ref<string>>('myColor') //获取
//获取,并且第二个参数可以设置默认值。方便子组件修改myColor.value值
const myColor = inject<Ref<string>>('myColor', ref('red))
二、示例:
//parent.vue
<template>
<div>
<p>这是父级组件</p>
<el-radio-group v-model="radio">
<el-radio label="red">红色</el-radio>
<el-radio label="yellow">黄色</el-radio>
<el-radio label="blue">蓝色</el-radio>
</el-radio-group>
<div class="box" :style="setStyle()"></div>
</div>
<Son></Son>
</template>
<script setup lang='ts'>
import { ref, provide } from 'vue'
import Son from '../components/Son.vue';
const radio = ref<string>('red')
provide('myColor',radio) //注入依赖
const setStyle = ()=>{
return {
backgroundColor:radio.value
}
}
</script>
<style scoped lang='scss'>
.box {
width: 200px;
height: 200px;
border: 1px solid #ccc;
transition: all 1s;
}
</style>
//son.vue
<template>
<div>
<p>这是儿子组件</p>
<div class="box" :style="setStyle()"></div>
</div>
<Grandson></Grandson>
</template>
<script setup lang='ts'>
import { inject } from 'vue'
import type { Ref } from 'vue';
import Grandson from './Grandson.vue';
const myColor = inject<Ref<string>>('myColor')
//设置背景颜色-方法一
const setStyle = ()=>{
return {
// backgroundColor:myColor?.value
}
}
</script>
<style scoped lang='scss'>
.box{
width: 200px;
height: 200px;
border: 1px solid #ccc;
// 设置背景颜色-方法二
background-color: v-bind(myColor);
transition: all 1s;
}
</style>
//grandSon.vue
<template>
<div>
<p>这是孙子组件</p>
<div class="box"></div>
</div>
</template>
<script setup lang='ts'>
import { inject } from 'vue'
const myColor = inject('myColor')
</script>
<style scoped lang='scss'>
.box{
width: 200px;
height: 200px;
border: 1px solid #ccc;
background-color: v-bind(myColor);
transition: all 1s;
}
</style>
三、子组件、孙子组件等,可以修改父组件传递过来的值
//grandson.vue
<template>
<div>
<p>这是孙子组件</p>
<el-button @click="changeColor">更改颜色</el-button>
<div class="box"></div>
</div>
</template>
<script setup lang='ts'>
import { inject,ref } from 'vue'
import type {Ref} from 'vue'
const myColor = inject<Ref<string>>('myColor',ref('red'))
const changeColor = ()=>{
myColor.value = 'green'
}
</script>
注意!!如果不允许子组件修改父组件传递的参数,则需要在父组件依赖注入的时候,用readonly修饰
//parent.vue
<script setup lang='ts'>
import { ref, provide, readonly } from 'vue'
import Son from '../components/Son.vue';
const radio = ref<string>('red')
provide('myColor',readonly(radio)) //注入依赖,用readonly修饰,不允许子组件修改值
</script>