一、基本用法:
import { ref, provide } from 'vue'
const radio = ref<string>('red')
provide('myColor',radio)
import { inject } from 'vue'
import type { Ref } from 'vue';
const myColor = inject<Ref<string>>('myColor')
二、示例:
<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>
<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 {}}</script>
<style scoped lang='scss'>
.box{width: 200px;height: 200px;border: 1px solid #ccc;background-color: v-bind(myColor);transition: all 1s;
}</style>
<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>