VUE3祖孙组件传值调用方法

VUE3祖孙组件传值调用方法

父子组件传参可以通过 propsemit 来实现,但是当组件的层次结构比较深时,propsemit 就太繁琐了。vue为了解决这个提出了 provide / Inject

下面利用代码演示如何使用

祖父组件:

<template>
	<div>
		<!--父组件-->
		<FatherDiv>
		
		</FatherDiv>
	</div>
</template>
<script setup>
import {
    
    ref, reactive,provide} from "vue";
import FatherDiv from './fatherDiv.vue'
const grandFatherData1 = ref('我是祖父组件数据');
const grandFatherFun1 = ()=>{
    
    
	console.log("我是祖父组件方法")
}
 provide('grandFatherData1',grandFatherData1.value ); //将数据和方法导出
 provide('grandFatherFun1',grandFatherFun1 );
</script>

父组件 fatherDiv.vue:

<template>
	<div>
		<!--子组件-->
		<Grandson>
		
		</Grandson>
	</div>
</template>
<script setup>
import {
    
    ref, reactive,provide} from "vue";
import Grandson from './grandson.vue'

</script>

孙子组件 grandson.vue:

<template>
	<div>
		<button @click="getGrandFatherData()">获取祖父组件数据</button>
	</div>
</template>
<script setup>
import {
    
    ref, reactive,inject} from "vue";
const fun1 = inject('grandFatherFun1') // 接受
const data1 = inject('grandFatherData1');

const getGrandFatherData = ()=>{
    
    
	fun1(); //调用方法
	console.log(data1); //调用数据
}
</script>

猜你喜欢

转载自blog.csdn.net/qq_37656005/article/details/127448616