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>
执行结果: