面试题答案
一键面试Provide/Inject 实现多层嵌套组件数据传递步骤
- 顶层组件提供数据:在顶层组件中使用
provide
选项来提供数据。 - 深层嵌套子组件注入数据:在深层嵌套的子组件中使用
inject
选项来注入顶层组件提供的数据。
关键代码示例
顶层组件(假设为 App.vue)
<template>
<div id="app">
<child-component></child-component>
</div>
</template>
<script>
import ChildComponent from './components/ChildComponent.vue';
export default {
name: 'App',
components: {
ChildComponent
},
provide() {
return {
themeColor: 'blue' // 主题颜色配置
};
}
};
</script>
深层嵌套子组件(假设 ChildComponent 下还有更深层嵌套的 GrandChildComponent.vue)
<template>
<div>
<grand-child-component></grand-child-component>
</div>
</template>
<script>
import GrandChildComponent from './GrandChildComponent.vue';
export default {
name: 'ChildComponent',
components: {
GrandChildComponent
}
};
</script>
最深层子组件(GrandChildComponent.vue)
<template>
<div>
<p>当前主题颜色: {{ themeColor }}</p>
</div>
</template>
<script>
export default {
name: 'GrandChildComponent',
inject: ['themeColor']
};
</script>
上述代码展示了如何在多层嵌套的 Vue 组件结构中,使用 Provide/Inject
来传递主题颜色配置信息。顶层组件 App.vue
通过 provide
提供 themeColor
,最深层子组件 GrandChildComponent.vue
通过 inject
注入并使用该数据。