业务背景
- 页面根组件有一些基础数据,在初始化阶段通过网络请求获取,保存到 data 中
- 第四层的的子孙组件需要依赖根组件的基础数据
- 为了避免重复的网络请求,需要一个传值方案将基础数据跨三个层级传递给子孙组件
传值方案
| 方案 | 实现过程 | 优点 | 缺点 |
|---|---|---|---|
| props | 通过 props 选项逐级传递 | 依赖关系清晰,一目了然 | 修改点较多,影响整条链路的所有组件 |
| provide/inject | 在页面根组件提供上下文,子孙组件按需注入 | 按需修改,影响较小 | 需保证命名不冲突,缺少属性的强约束 |
示例代码
传递根组件的 vue 实例作为上下文,子孙组件根据上下文获取属性,是可响应的。
/* provide/inject 传值 */
// src/pages/MyPage/index.vue
<template>
<div>
<identity-tab></identity-tab>
</div>
</template>
<script>
import IdentityTab from './IdentityTab.vue'
export default {
provide () {
return { context: this }
},
data () {
showAage: true
},
components: {
IdentityTab
}
}
</script>
// src/pages/MyPage/IdentityTab.vue
<template>
<div>
<basic-info></basic-info>
</div>
</template>
<script>
import BasicInfo from './BasicInfo.vue'
export default {
components: {
BasicInfo
}
}
// src/pages/MyPage/BasicInfo.vue
<template>
<div>
<div>{{ name }}</div>
<div v-if="context.showAge">{{ age }}</div>
</div>
</template>
<script>
export default {
inject: ['context']
}
</script>