【vue3】依赖注 provide、inject(父组件与儿子、孙子、曾孙子组件之间的传值)

一、基本用法:


//父组件
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') //获取

二、示例:

【vue3】依赖注 provide、inject(父组件与儿子、孙子、曾孙子组件之间的传值)_第1张图片


//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>

你可能感兴趣的:(vue3,javascript,前端,vue.js)