原理
- Vue 响应式原理基础:Vue 通过
Object.defineProperty
或 Proxy
(Vue3 中)将数据转换为响应式,在数据访问和修改时进行拦截,通知依赖该数据的组件进行更新。
- 依赖注入中的响应式问题:在依赖注入中,
provide
提供的数据默认情况下,inject
接收后不是响应式的,因为直接传递的数据是值传递,没有建立响应式依赖关系。
- 保持响应式的原理:要使
inject
接收的数据保持响应式,需要将 provide
的数据包装成一个响应式对象(如 ref
或 reactive
,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>