通常我们使用props进行父子之间的数据传递,但是如果组件嵌套层级较深,一层一层往下传递将会变的非常繁琐,有没有一种手段可以把这个过程简化一下呢,有的,就是我们马上要学习的provide 和 inject,它们配合起来可以方便的完成从顶层组件向任意底层组件传递数据的效果
实现步骤
-
顶层组件在setup方法中使用
provide函数
提供数据provide('key',数据)
-
任何底层组件在setup方法中使用
inject函数
获取数据const data = inject('key')
代码如下:
爷爷组件
<template>
<father></father>
</template>
<script>
import Father from '@/components/Father'
import { provide } from 'vue'
export default {
components: {
Father
},
setup() {
let name = 'lichenfei'
// 使用provide配置项注入数据 key - value
provide('name', name)
}
}
</script>
孙子组件
<template>
我是子组件
{{ name }}
</template>
<script>
import { inject } from 'vue'
export default {
setup() {
const name = inject('name')
return {
name
}
}
}
</script>