学习vue3:跨组件通信(provide+inject)
目录
一,关于跨组件通信概述
二,跨组件传值
案例1(爷传孙)
三,跨组件传函数
案例2(爷传孙)
疑问:孙子传给爷爷是否可行呢?
一,关于跨组件通信概述
之前我们学习了父子组件的传值,它仅仅只是两个组件嵌套传递数据,跨组件通信,则是多个组件传递数据。如:现在有三个组件:App.vue,father.vue,son.vue,我把App.vue看作爷爷,father.vue看作父亲,son.vue看作儿子。现在我要将数据从爷爷传给孙子,就可以使用跨组件通信。
提示:
跨组件通信:使用 provide+inject的方式适用于需要跨层级共享数据的场景
但需注意不要滥用。如果组件层级较深,且需要在多个组件之间共享状态,可以使用 Vuex 或 Pinia 等状态管理工具(后面也会讲)
二,跨组件传值
案例1(爷传孙)
App.vue
<script setup>
import father from './views/father.vue';
import { provide,ref,reactive} from 'vue';
const data=ref(1234567890)
const dataObj=reactive({name:'张三',age:20})
provide('data',data)
provide('dataObj',dataObj)
</script>
<template>
<father></father>
</template><style scoped></style>
father.vue
<template><div>爷爷传给父亲的基本数据值:{{ father }}<br/>
爷爷传给父亲的对象值:{{ father1 }}</div></template><script setup>import { inject,ref } from 'vue';const father = inject('data');const father1 = inject('dataObj');const a=ref('')a.value=father.valueconsole.log(a.value)a.value=father1.nameconsole.log(a.value)</script><style lang="scss" scoped></style>
son.vue
<template><div>
爷爷传给孙子的基本数据:{{ parent }}<br>爷爷传给孙子的对象数据:{{ parent2 }}</div>
</template><script setup>
import { inject } from 'vue';
const parent = inject('data');
const parent2 = inject('dataObj');
console.log(parent2);
</script><style lang="scss" scoped></style>
测试结果
三,跨组件传函数
案例2(爷传孙)
son.vue
<template><button @click="count">爷爷传递的函数</button>
</template><script setup>
import { inject ,provide,ref} from 'vue';
const count=inject('count')
</script><style lang="scss" scoped></style>
App.vue
<script setup>
import father from './views/father.vue';
import { provide, inject,ref,reactive} from 'vue';
const count=ref(0)
const countNum=()=>{count.value++
}
provide('count',countNum)
</script><template>
<father>
</father>
<br/>
<h4>当孙子点击爷爷发送自增函数,数据:{{ count }}</h4>
</template><style scoped></style>
测试结果
总结:跨组件通信,无法做到孙子传给爷爷,但在组件中可以多次使用provide 或inject函数
疑问:孙子传给爷爷是否可行呢?
案例3(孙传爷)
son.vue
<template><div>爷爷传给孙子的基本数据:{{ parent }}<br>爷爷传给孙子的对象数据:{{ parent2 }}</div>
</template><script setup>
import { inject ,provide,ref} from 'vue';
const parent = inject('data');
const parent2 = inject('dataObj');
console.log(parent2);
const son = ref(11111)
provide("dataSon",son)
</script><style lang="scss" scoped></style>
App.vue
<script setup>
import father from './views/father.vue';
import { provide, inject,ref,reactive} from 'vue';
const data=ref(1234567890)
const dataObj=reactive({name:'张三',age:20})
provide('data',data)
provide('dataObj',dataObj)
const son=inject('dataSon')
console.log("son:",son)
</script><template>
<father>
</father>
</template><style scoped></style>
测试结果