先来个需求
爷组件中有一份数据 传递给孙组件直接使用
实现步骤
1.顶层组件在setup方法中使用provide函数提供数据
2.任何底层组件在setup方法中使用inject函数获取数据
代码实现
App.vue
<template>
<div>
<Father></Father>
</div>
</template>
<script>
import { provide } from 'vue'
import Father from './components/Father'
export default {
components: {
Father
},
setup(){
const name ='小李'
// 使用provide配置项注入数据 key - value 第一个name是命名
provide('name',name)
}
}
</script>
Father.vue
<template>
<div>
我是父组件
<Son></Son>
</div>
</template>
<script>
import Son from '../components/Son'
export default {
components:{
Son
}
}
</script>
Son.vue
<template>
<div>
我是孙组件
{{name}}
</div>
</template>
<script>
import { inject } from 'vue'
export default {
setup(){
//使用变量接受
const name = inject('name')
return {name}
}
}
</script>
实际上,只要是后代组件,都可以获取顶层组件提供的数据