Vue3 provide 与 inject跨组件传值

provide与inject的作用

provide和inject提供依赖注入,实现跨层级组件(祖孙)间通信。

祖孙组件传递数据指的是中间隔了一层或多层组件,父子也可使用(但是更推荐使用props)

根组件:

<template>

    <!-- provide与inject -->
    <div class="Ancestor">
        <h3>我是根组件 想要传递的数据是 person对象--{{person}}
        </h3>
        
        <child-test></child-test> 
    </div>
    
</template>

<script>
import childTest from '@/components/childTest'

import { reactive,provide } from 'vue';
export default {
    name: 'Vue3TestHome',
    components: {
        childTest
    },
    setup() {

        let person = reactive({
            name:'张三',
            age:18,
            sex:'男',
        })
        // 给自己的后代组件传递数据
        provide('person',person)

        return {
            person,
        }
    },
    
};
</script>

<style lang="scss" scoped>
.Ancestor{
    text-align: center;
    background: pink;
    height: 300px;
    width: 1000px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)
}
</style>

子组件:

<template>
	<div class="child">
		<h2>我是子组件</h2>
		<grand-son></grand-son>
	</div>
</template>

<script>
import grandSon from '@/components/grandSon';

	export default {
		name:'childTest',
		components:{
			grandSon
		},
	}
</script>

<style lang="scss" scoped>
.child{
	text-align: center;
	background: skyblue;
	height: 200px;
	width: 800px;
	box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)
}
</style>

孙组件:

<template>
    <div class="grand-son">
        <h2>我是孙组件 接收数据:{{person.name}}--{{person.age}}--{{person.sex}</h2>
    </div>
</template>

<script>
/* 引入组合api */
import {inject} from 'vue';
	export default {
		setup(){
            // 函数的返回值就是我们所接收的值
			let person = inject('person')

			return {
                person
            }
		}
	}
</script>

<style lang="scss" scoped>
.grand-son{
    text-align: center;
	background: #ccc;
	height: 100px;
    width: 600px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)
}
</style>

执行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值