在 Vue 3 中,provide 和 inject 是用于在组件树中共享状态的工具。provide 用于提供数据,inject 用于接收数据。为了使提供的数据是响应式的,我们可以利用 Vue 3 的 reactive 或 ref 来实现。
以下是一个详细的示例,展示如何使用 provide 和 inject 以及如何使数据响应式。
示例代码
父组件 (Provider)
<template>
<div>
<h1>Parent Component</h1>
<button @click="increment">Increment</button>
<p>Count: {{ state.count }}</p>
<ChildComponent />
</div>
</template>
<script>
import { reactive, provide } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default {
name: 'ParentComponent',
components: {
ChildComponent
},
setup() {
const state = reactive({
count: 0
});
const increment = () => {
state.count++;
};
provide('state', state);
provide('increment', increment);
return {
state,
increment
};
}
};
</script>
子组件 (Child)
<template>
<div>
<h2>Child Component</h2>
<button @click="increment">Increment from Child</button>
<p>Count from Parent: {{ state.count }}</p>
</div>
</template>
<script>
import { inject } from 'vue';
export default {
name: 'ChildComponent',
setup() {
const state = inject('state');
const increment = inject('increment');
return {
state,
increment
};
}
};
</script>
代码讲解
-
父组件 (ParentComponent):
-
模板部分:
- 包含一个按钮和一个显示计数的段落。
- 包含子组件
ChildComponent。
-
脚本部分:
- 使用
reactive创建响应式状态对象state,其中包含一个count属性。 - 定义一个
increment函数来增加count。 - 使用
provide方法将state和increment函数提供给子组件。 - 在
setup函数中返回state和increment以便在模板中使用。
- 使用
-
-
子组件 (ChildComponent):
-
模板部分:
- 包含一个按钮和一个显示从父组件传递过来的计数的段落。
-
脚本部分:
- 使用
inject方法接收父组件提供的state和increment。 - 在
setup函数中返回state和increment以便在模板中使用。
- 使用
-
使数据响应式
在 Vue 3 中,reactive 和 ref 都可以用于创建响应式数据:
reactive:用于创建包含多个属性的响应式对象。ref:用于创建包含单个属性的响应式对象。
在上述示例中,我们使用了 reactive 来创建一个包含 count 属性的响应式对象 state。这样,当 count 的值改变时,依赖于 count 的所有组件都会自动更新。
总结
通过使用 provide 和 inject,我们可以在组件树中方便地共享状态。结合 reactive 或 ref,我们可以确保这些状态是响应式的,从而在状态变化时自动更新相关的组件。