MST

星途 面试题库

面试题:Vue依赖注入中的响应式问题

在Vue依赖注入中,如果`provide`的数据发生变化,`inject`接收的数据如何保持响应式?请阐述原理并给出实现的关键代码片段。
42.3万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试

原理

  1. Vue 响应式原理基础:Vue 通过 Object.definePropertyProxy(Vue3 中)将数据转换为响应式,在数据访问和修改时进行拦截,通知依赖该数据的组件进行更新。
  2. 依赖注入中的响应式问题:在依赖注入中,provide 提供的数据默认情况下,inject 接收后不是响应式的,因为直接传递的数据是值传递,没有建立响应式依赖关系。
  3. 保持响应式的原理:要使 inject 接收的数据保持响应式,需要将 provide 的数据包装成一个响应式对象(如 refreactive,Vue3 中;Vue2 中使用 Vue.observable),这样当包装对象内部的数据变化时,Vue 能够检测到并通知依赖它的组件更新。

关键代码片段(Vue3)

父组件(提供数据)

<template>
  <div>
    <button @click="updateValue">Update Value</button>
    <ChildComponent />
  </div>
</template>

<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';

const sharedValue = ref('initial value');

const updateValue = () => {
  sharedValue.value = 'new value';
};

provide('sharedValue', sharedValue);
</script>

子组件(接收数据)

<template>
  <div>
    <p>Shared Value: {{ sharedValue }}</p>
  </div>
</template>

<script setup>
const sharedValue = inject('sharedValue');
</script>

关键代码片段(Vue2)

父组件(提供数据)

<template>
  <div>
    <button @click="updateValue">Update Value</button>
    <ChildComponent />
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: { ChildComponent },
  data() {
    return {
      sharedValue: 'initial value'
    };
  },
  created() {
    this.$provide('sharedValue', this.$observable(this.sharedValue));
  },
  methods: {
    updateValue() {
      this.sharedValue = 'new value';
    }
  }
};
</script>

子组件(接收数据)

<template>
  <div>
    <p>Shared Value: {{ sharedValue }}</p>
  </div>
</template>

<script>
export default {
  inject: ['sharedValue']
};
</script>