MST

星途 面试题库

面试题:Vue中Provide/Inject结合Composition API如何实现数据传递

请描述在Vue项目中,使用Provide/Inject结合Composition API实现父组件向深层子组件传递数据的具体步骤,并给出一个简单示例代码。
32.9万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试
  1. 具体步骤

    • 在父组件中
      • 使用provide函数提供数据。在Composition API中,provide函数接受两个参数,第一个是要提供的数据的键,第二个是要提供的数据值。
      • 这个数据可以是响应式数据(通过refreactive创建),也可以是普通数据。
    • 在子组件中
      • 使用inject函数注入父组件提供的数据。inject函数接受一个参数,即父组件提供数据时使用的键。
      • 如果注入的数据是响应式的,在子组件中可以直接使用它,响应式数据的变化会自动更新视图。
  2. 示例代码

    • 父组件(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>