← 返回首页
Vue3基础教程(三十二)
发表时间:2021-08-13 17:25:47
provide 与 inject

provide和inject提供依赖注入,功能类似 2.x 的provide/inject。实现跨层级组件(祖孙)间通信。

实例:

App.vue

<template>
    <h2>provide和inject效果</h2>
    <hr>
    <div>当前颜色: {{color}}</div>
    <button @click="color='red'">红</button>
    <button @click="color='green'">绿</button>
    <button @click="color='blue'">蓝</button>
    <hr>
    <Child></Child>
</template>

<script lang="ts">

    import Child from '@/components/Child.vue'
    import {
        defineComponent,
        ref,
        provide
    } from 'vue'

    export default {
        name: 'App',
        components:{
            Child
        },
        setup () {
            const color = ref('red');
            provide('color', color)
            return {
               color
            }
        }
    }

</script>

Child.vue

<template>
    <h2>Child</h2>
    <hr>
    <GrandSon></GrandSon>
</template>

<script lang="ts">
    import { computed, defineComponent, Ref, toRef } from 'vue'
    import GrandSon from '@/components/GrandSon.vue';
    const component = defineComponent({
        name: 'Child',
        components:{
          GrandSon
        },
        setup () {
           console.log('GrandSon setup()...');
        }
    })

    export default component
</script>

GrandSon.vue

<template>
    <h2 :style="{color}">GrandSon</h2>
</template>

<script>
    import { inject } from 'vue'
    export  default {
        name: "GrandSon",
        setup() {
            const color = inject('color')
            return {
                color
            }
        }
    }
</script>

运行效果: