返回
Vue 3 组合式 provide/inject
前端
2023-12-26 07:58:24
Vue 3 组合式 provide/inject
在之前的章节,我们讲了选项式的 提供与注入,今天我们继续讲组合式提供与注入。
我们也可以在组合式 API 中使用 provide/inject。两者都只能在当前活动实例的 setup() 期间调用。
假设我们要重写以下代码,其中包含一个 TemplateM 组件,该组件使用组合式 API 定义:
<template>
<div>
<h1>{{ msg }}</h1>
<p v-if="showInfo">{{ info }}</p>
<button @click="showInfo = !showInfo">Toggle Info</button>
</div>
</template>
<script>
export default {
setup() {
const msg = Vue.ref('Hello World!');
const showInfo = Vue.ref(false);
const info = 'This is some information.';
return {
msg,
showInfo,
info
};
}
};
</script>
为了在组件之间共享 msg
和 showInfo
,我们可以使用组合式 provide/inject
:
1. 使用 provide
在组件中提供数据:
export default {
setup() {
const msg = Vue.ref('Hello World!');
const showInfo = Vue.ref(false);
const info = 'This is some information.';
provide('msg', msg);
provide('showInfo', showInfo);
return {
info
};
}
};
2. 在其他组件中使用 inject
接收数据:
<script>
export default {
setup() {
// 使用 inject 接收数据
const msg = inject('msg');
const showInfo = inject('showInfo');
return {
msg,
showInfo
};
}
};
</script>
3. 使用 <provide>
和 <inject>
组件:
Vue 3 还提供了 <provide>
和 <inject>
组件,可以简化组合式 provide/inject
的使用:
<provide>
<template>
<div>
<h1>{{ msg }}</h1>
<p v-if="showInfo">{{ info }}</p>
<button @click="showInfo = !showInfo">Toggle Info</button>
</div>
</template>
<script>
export default {
setup() {
const msg = Vue.ref('Hello World!');
const showInfo = Vue.ref(false);
const info = 'This is some information.';
return {
msg,
showInfo,
info
};
}
};
</script>
</provide>
<inject>
<template>
<p>Injected: {{ msg }} - {{ showInfo }}</p>
</template>
<script>
export default {
setup() {
// 使用 inject 接收数据
const msg = inject('msg');
const showInfo = inject('showInfo');
return {
msg,
showInfo
};
}
};
</script>
</inject>
注:
- 在组件中使用
provide/inject
时,确保在 setup() 函数中调用它们。 - 在接收组件中使用
inject
时,返回一个包含注入数据的对象。 <provide>
和<inject>
组件只在 Vue 3 中可用。
通过使用组合式 provide/inject
,我们可以轻松地在组件之间共享数据,从而实现组件通信。