学习优先度:★★★☆☆
难易度:★★★☆☆
Vue 3 的 provide 和 inject 允许您在组件之间共享数据,包括反应值,而无需prop drilling。
下面介绍如何使用 provide 和 inject 在父组件和子组件之间共享反应值。
【代码示例】
// main.js
import { createApp, reactive } from 'vue';
import App from './App.vue';
const app = createApp(App);
// Adding a global reactive object
app.provide('globalState', reactive({ count: 0 }));
app.mount('#app');
vue
<!-- App.vue -->
<template>
<div>
<h1>Count: {{ globalState.count }}</h1>
<button @click="incrementCount">Increment</button>
<ChildComponent />
</div>
</template>
<script>
import { inject } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default {
name: 'App',
components: {
ChildComponent
},
setup() {
const globalState = inject('globalState');
const incrementCount = () => {
globalState.count++;
};
return {
globalState,
incrementCount
};
}
};
</script>
<!-- ChildComponent.vue -->
<template>
<div>
<h2>Child Count: {{ globalState.count }}</h2>
<button @click="incrementCount">Increment in Child</button>
</div>
</template>
<script>
import { inject } from 'vue';
export default {
name: 'ChildComponent',
setup() {
const globalState = inject('globalState');
const incrementCount = () => {
globalState.count++;
};
return {
globalState,
incrementCount
};
}
};
</script>
【执行结果】
Count: 0
[Click "Increment" button]
Count: 1
Child Count: 1
在上面的示例中,主应用程序实例中使用 provide 来提供一个反应式 globalState 对象。App.vue 和 ChildComponent.vue 中使用 inject 来访问所提供的 globalState。
【补充】
在大型应用程序中,提供和注入反应值尤其有用,因为在大型应用程序中,prop drilling 会变得非常麻烦。该功能通过解耦组件,使代码更简洁、更易于维护。