当一个设置页面包含多层布局、分组和输入组件时,逐层传递不属于中间组件的 props 会使接口越来越复杂。Vue 的 provide 与 inject 可以将上下文提供给后代组件。本文以局部配置编辑器为例,讨论如何保持依赖范围、状态所有权和 TypeScript 类型一致。
1. 识别真正的上下文依赖
上下文适合由某个业务子树共同使用的能力,例如表单配置、当前编辑对象和只读权限。不适合把所有全局状态都藏进依赖注入。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/216c279898f09d9e688dca51a15f5f74bdfcf32a">
<SettingsProvider><SettingsToolbar /><SettingsGroups /></SettingsProvider>
</div>
2. 定义类型安全的注入键
字符串键可能与其他模块冲突。使用 Symbol 配合 InjectionKey,让提供者和消费者共享同一类型契约。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/742516d897a5e67cb7271a8f575fc6e0fe3056b4">
<section aria-label="设置上下文"><h2>工作区设置</h2></section>
</div>
import type {
InjectionKey, Ref } from 'vue';
export interface SettingsContext {
readonly disabled: Readonly<Ref<boolean>>;
update: (key: string, value: boolean) => void;
}
export const settingsKey: InjectionKey<SettingsContext> = Symbol('settings');
3. 由提供者维护响应式状态
provide 可以直接提供 ref。将修改方法也由提供者暴露,使后代组件不必直接操作整份对象。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/ff3614ed36c1ebaeabd92a47ed560eed4799e07a">
<section><slot /></section>
</div>
<script setup lang="ts">
import { provide, ref, readonly } from 'vue';
import { settingsKey } from './settings-context';
const disabled = ref(false);
const options = ref<Record<string, boolean>>({});
function update(key: string, value: boolean) {
if (!disabled.value) options.value = { ...options.value, [key]: value };
}
provide(settingsKey, { disabled: readonly(disabled), update });
</script>
4. 封装必须存在的依赖
如果组件必须位于提供者内部,缺少依赖时应快速报告明确错误,而不是在后续模板渲染时出现 undefined。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/d3fbbd526808b9378d86a88f1199eafe7e855613">
<p v-if="disabled" role="status">当前设置为只读</p>
</div>
import {
inject } from 'vue';
import {
settingsKey } from './settings-context';
export function useSettings() {
const context = inject(settingsKey);
if (!context) throw new Error('SettingsProvider is required');
return context;
}
5. 让叶子组件只发送操作意图
输入组件可以依赖当前上下文是否允许修改,再调用 update。当前值仍可通过 props 传入,从而保留明确的组件数据接口。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/3d3bc9b70970e89a55d9d81e36e7cbadb5ce8a83">
<label>
<input type="checkbox" :checked="value" :disabled="disabled" @change="change" />
{
{ label }}
</label>
</div>
const {
disabled, update } = useSettings();
function change(event: Event) {
update(props.optionKey, (event.target as HTMLInputElement).checked);
}
6. 正确处理嵌套提供者
同一个注入键可以在组件树中多次提供,消费者会获取最近的祖先提供者。这适合独立编辑两个工作区,但需要避免无意覆盖外层上下文。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/4e61fb1b816f56cbfc14d974992112e3abe20a43">
<SettingsProvider>
<SettingsGroup title="外层配置" />
<SettingsProvider><SettingsGroup title="独立配置" /></SettingsProvider>
</SettingsProvider>
</div>
7. 为可选能力提供合理默认值
不是所有依赖都需要强制存在。例如独立展示的组件可以拥有默认格式化函数。默认值应该满足类型契约,不应在多个实例间共享可变对象。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/71a691dfd4be014c98dfd53761b08a06dc9174e9">
<p>{
{ formatValue(displayValue) }}</p>
</div>
const formatValue = inject(formatterKey, (value: unknown) => String(value));
8. 避免隐式的跨层写入
注入值的响应式能力不会自动保证业务约束。若保存涉及权限或数据校验,提供者的方法必须遵循同一业务规则,服务端仍负责最终授权。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/6d95e8570561277e9958e2c7218b64646f701ac4">
<button type="button" :disabled="disabled" @click="submitSettings">保存设置</button>
<p v-if="error" role="alert">{
{ error }}</p>
</div>
9. 使用测试提供者隔离外部依赖
测试叶子组件时可以注入模拟上下文,检查点击是否触发预期的 update,而不必挂载整个设置页面。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/115366d0e61d87541a12f1b18745079ac292f282">
<SettingSwitch option-key="notifications" label="启用通知" :value="false" />
</div>
mount(SettingSwitch, {
props: {
optionKey: 'notifications', label: '启用通知', value: false },
global: {
provide: {
[settingsKey as symbol]: {
disabled: ref(false), update: vi.fn() } } }
});
10. 决定何时升级为全局状态
局部提供者随业务子树销毁,适合短生命周期配置。需要跨页面持久化的数据才考虑更高层的状态服务。不要因传递 props 经过两层就必然引入依赖注入。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/01c942d8579e23b288f501b962138fff6b7afa56">
<section><h2>高级配置</h2><SettingsProvider><AdvancedSettings /></SettingsProvider></section>
</div>
总结
provide 与 inject 适合表达组件树范围内的依赖。类型化注入键、只读状态和集中修改入口可以让这种跨层通信保持可读性,同时避免演变成难以定位的全局隐式状态。