面试题答案
一键面试-
具体步骤:
- 在父组件中:
- 使用
provide
函数提供数据。在Composition API中,provide
函数接受两个参数,第一个是要提供的数据的键,第二个是要提供的数据值。 - 这个数据可以是响应式数据(通过
ref
或reactive
创建),也可以是普通数据。
- 使用
- 在子组件中:
- 使用
inject
函数注入父组件提供的数据。inject
函数接受一个参数,即父组件提供数据时使用的键。 - 如果注入的数据是响应式的,在子组件中可以直接使用它,响应式数据的变化会自动更新视图。
- 使用
- 在父组件中:
-
示例代码:
- 父组件(App.vue):
<template>
<div id="app">
<ChildComponent />
</div>
</template>
<script setup>
import { provide, ref } from 'vue';
import ChildComponent from './components/ChildComponent.vue';
const sharedData = ref('Hello from parent');
provide('sharedData', sharedData);
</script>
<style>
#app {
font - family: Avenir, Helvetica, Arial, sans - serif;
-webkit - font - smoothing: antialiased;
-moz - osx - font - smoothing: grayscale;
text - align: center;
color: #2c3e50;
margin - top: 60px;
}
</style>
- 子组件(ChildComponent.vue):
<template>
<div>
<p>{{ injectedData }}</p>
</div>
</template>
<script setup>
import { inject } from 'vue';
const injectedData = inject('sharedData');
</script>
<style scoped>
div {
border: 1px solid gray;
padding: 10px;
margin: 10px;
}
</style>