vue3中inject和provide双向沟通

一:使用说明:指组件之间的传值,尤其是祖孙之间的组件交互。provide是一级组件传过来的数值,inject是下一级组件获取的值

二:示例

//one.vue

<template>
	<two></two>
	<div style="background-color: #2C3E50;color: #fff;padding: 20px;margin: 10px;">
		<p>一级组件的值:{{variableOne}}</p>
		<button @click="variableOne = '1111'">一级按钮</button>
	</div>
</template>
<script>
	import two from './components/two.vue'
	import {
		ref,
		provide,
		defineComponent
	} from 'vue'
	export default defineComponent({
		name: 'lycApp',
		components: {
			two
		},
		setup(prop, context) {
			const variableOne = ref('0000')
			provide('getVariable', variableOne)
			return {
				variableOne
			}
		}
		// provide(){ //这是传值的另一种写法,效果一样
		// 	return{
		// 		getContext:()=>({
		// 			variable:this.variable
		// 		})
		// 	}
		// }
	})
</script>

//two.vue

<template>
	<three></three>
	<div style="background-color: chocolate;color: #fff;padding: 20px;margin: 10px;">二级组件的值:{{variableTwo1}}</div>
</template>

<script>
	import three from './three.vue'
	import {computed,inject} from 'vue'
	export default{
		name:'two',
		components:{
			three
		},
		// inject:['getContext'],
		// computed:{
		//   	sonContext(){
		// 		return this.getContext()
		// 	}
		// },
		setup(props,context){
			const variableTwo = inject('getVariable')
			const variableTwo1 = computed(()=>{
				return variableTwo.value
			})
			return{
				variableTwo1
			}
		}
	}
</script>

//three

<template>
	<div style="background-color: darkcyan;color: #fff;padding: 20px;margin: 10px;">
		<div>三级组件的值:{{variableThree1}}</div>
		<button @click="changeVariable">三级按钮</button>
	</div>
</template>

<script>
	import {ref,inject,computed} from 'vue'
	export default {
		name:'three',
		setup(props,context){
			const variableThree = inject('getVariable')
			const variableThree1 = computed(()=>{
				return variableThree.value
			})
			const changeVariable = ()=>{
				variableThree.value = '3333'
			}
			return{
				variableThree1,
				changeVariable
			}
		}
	}
</script>

<style>
</style>

//效果图
在这里插入图片描述
点击一级按钮按钮,一二三级的值都会变成1111。点击三级按钮,一二三级的值都会变成3333

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值