面试题答案
一键面试1. Provide/Inject 机制
provide
选项用于在父组件中提供数据,该数据可以被其子孙组件通过inject
选项注入使用。provide
的值可以是一个对象或返回一个对象的函数。inject
选项在子孙组件中接收数据,它可以是一个数组或一个对象(对象形式可以设置默认值等)。
2. Vue 插槽
- Vue 插槽用于在组件模板中预留位置,以便父组件传入内容进行填充。
- 有默认插槽(
<slot>
)和具名插槽(<slot name="xxx">
)。
3. 结合实现数据传递与展示
- 假设我们有一个祖孙组件结构,
GrandParent
为父组件,Parent
为中间组件,Child
为子孙组件。
代码示例
<!-- GrandParent.vue -->
<template>
<div>
<parent>
<template v-slot:default>
<child></child>
</template>
</parent>
</div>
</template>
<script>
import Parent from './Parent.vue';
export default {
components: { Parent },
provide() {
return {
grandParentData: '这是来自祖父组件的数据'
};
}
};
</script>
<!-- Parent.vue -->
<template>
<div>
<slot></slot>
</div>
</template>
<script>
import Child from './Child.vue';
export default {
components: { Child }
};
</script>
<!-- Child.vue -->
<template>
<div>
<slot name="specificSlot">
默认内容,如果父组件没有填充该插槽
</slot>
</div>
</template>
<script>
export default {
inject: ['grandParentData']
};
</script>
在使用 GrandParent
组件的父级组件中:
<template>
<div>
<grand - parent>
<template v - slot:default>
<child>
<template v - slot:specificSlot>
{{ grandParentData }}
</template>
</child>
</template>
</grand - parent>
</div>
</template>
<script>
import GrandParent from './GrandParent.vue';
export default {
components: { GrandParent },
inject: ['grandParentData']
};
</script>
这样,GrandParent
组件的数据 grandParentData
通过 provide/inject
传递到了 Child
组件,并在 Child
组件的 specificSlot
插槽位置展示。