vue3跨级组件通信方法(详解provide和inject函数)
vue3中provide和inject函数提供依赖注入,功能类似 vue2.x 的provide/inject,实现跨层级组件(祖孙)间通信。
子或孙子组件接收到的数据可以用于读取显示,也可以进行修改,同步修改父(祖)组件的数据。
注意:无论子组件是否接收了该数据,孙子组件都可使用inject接收修改该数据。
(祖)父组件代码:
<template>
<div style="font-size: 14px">
<h3>测试provide与inject跨层级组件(祖孙)间通信</h3>
<Child />
</div>
</template>
<script>
import {
defineComponent,
reactive,
onMounted,
toRefs,
provide,
} from 'vue'
import Child from './Child.vue'
// vue3.0语法
export default defineComponent({
name: '父组件名',
components: {
Child,
},
setup() {
const state = reactive({
id: '',
user: {
name: '张三',
age: 0,
},
})
onMounted(() => {
// 模拟一个接口请求
setTimeout(() => {
state.id = '父组件请求接口得来的id'
state.user = {
name: '张三丰',
age: 18,
}
}, 2000)
})
provide('state', state)
return {
...toRefs(state),
}
},
})
</script>子组件代码:
<template>
<div style="font-size: 14px;background: skyblue;">
<!-- 子组件内容 -->
<h3>子组件</h3>
<p>子组件inject接收到的state{{ state }}</p>
</div>
<Grandson />
</template>
<script>
import { defineComponent, onMounted, inject } from 'vue'
import Grandson from './Grandson.vue'
// vue3.0语法
export default defineComponent({
name: '子组件名',
components: {
Grandson
},
setup() {
const state = inject('state')
onMounted(() => {
console.log('onMounted Child', state)
})
return {
state
}
},
})
</script>孙子组件代码:
<template>
<div style="font-size: 14px; background: pink">
<!-- 孙子组件内容 -->
<h3>孙子组件</h3>
<p>孙子组件inject接收到的state{{ state }}</p>
<button @click="changeUser">修改父组件传来信息</button>
</div>
</template>
<script>
import { defineComponent, onMounted, inject } from 'vue'
// vue3.0语法
export default defineComponent({
name: '孙子组件名',
setup() {
const state = inject('state')
function changeUser() {
state.id = '孙子组件修改后的id'
state.user.name = '小明'
state.user.age = 22
}
onMounted(() => {
console.log('onMounted Grandson', state)
})
return {
state,changeUser
}
},
})
</script>初始页面效果:
初始页面显示结果:子和孙子组件都接收到了同样的数据显示。

2秒后(祖)父修改了数据页面效果:
2秒后页面显示结果:子和孙子组件都接收的数据同步发生了修改。

点击孙子组件的修改父组件传来信息按钮修改数据后》页面效果:
孙子组件将接收的数据修改后,父(祖父)的数据也同步被修改。
除注明外的文章,均为来源:老汤博客,转载请保留本文地址!
原文地址:https://tangjiusheng.cn/vue/14608.html
原文地址:https://tangjiusheng.cn/vue/14608.html
