根上下文
用 defineRootContext 和 useRootContext 共享和使用根状态
根上下文用于在 App.vue 中定义应用级状态,并提供给页面、组件或应用内其他文件使用。它适合承载应用骨架相关状态,而不是替代所有业务状态管理。
能力定位
根上下文解决的是跨页面读取应用根状态的问题。
典型场景:
- 主题状态。
- 应用外壳方法。
- 应用共享弹窗。
- 应用级共享的状态。
defineRootContext
在 App.vue 中无需导入,可以直接使用 defineRootContext() 定义共享状态。
src/App.vue
<script setup>
const { title, count, increment, isDark } = defineRootContext(() => {
const title = ref("Hello Oiyo");
const count = ref(0);
function increment() {
count.value += 6;
}
const isDark = useSystemDark();
return { title, count, increment, isDark };
});
</script>
工厂函数在 App.vue 的 <script setup> 作用域内执行,可以继续访问局部变量和自动导入的 API。返回的对象就是对外暴露的根上下文。
返回的状态需要显式接收(解构或赋值给变量)后,才能在
App.vue 模板中使用。App.vue 模板只能读取 <script setup> 中存在的绑定。用于定义共享状态的
defineRootContext 方法只允许在 App.vue 中使用。useRootContext
通过 useRootContext 可以在 页面、组件 或 应用内任意文件 中无需导入,直接消费 defineRootContext() 定义的共享状态。
应用骨架使用
这里的应用骨架指
App.vue 的 <template> 部分。在 App.vue 内,直接使用 defineRootContext() 接收到的变量:
src/App.vue
<script setup>
const { count, increment } = defineRootContext(() => {
const count = ref(0);
function increment() {
count.value += 1;
}
return { count, increment };
});
</script>
<template>
<view @click="increment"> 当前计数:{{ count }} </view>
</template>
页面中使用
页面使用 useRootContext() 读取根上下文。
src/pages/home/index.vue
<script setup lang="ts">
const { title, increment } = useRootContext<{
title: Ref<string>;
increment: () => void;
}>();
onLoad(() => {
console.log("生命周期中使用", title.value);
});
</script>
<template>
<view>{{ title }}</view>
<view @click="increment"> 模板中触发方法 </view>
</template>
useRootContext() 依赖 App.vue 的 setup 完成。不要在模块顶层直接解构,否则会抛出「根上下文尚未就绪」的错误。把调用放到 setup、composable 或中间件函数内部。应用文件中使用
store、composable 等应用内文件可以读取根上下文。
export const useAppStore = defineStore("oiyo-app", () => {
const { title } = useRootContext<{ title: Ref<string> }>();
const hey = computed(() => `你好 - ${title.value}`);
return { hey };
});
export const useCount = () => {
const { count } = useRootContext<{ count: Ref<number> }>();
const double = computed(() => count.value * 2);
return { double };
};
类型标注
useRootContext() 的泛型是可选的:
- 不传泛型时,使用自动生成的
OiyoRootContext类型。 - 传泛型时,按当前文件需要的字段手写类型。
自动生成类型
在 App.vue 中声明并导出根上下文类型,再把它传给 defineRootContext<T>():
src/App.vue
<script setup lang="ts">
export interface RootContext {
title: Ref<string>;
count: Ref<number>;
increment: () => void;
}
defineRootContext<RootContext>(() => {
// ...
});
</script>
之后页面里直接调用 useRootContext() 就能获得完整类型:
src/pages/home/index.vue
const { title, increment } = useRootContext();
手动标注
读取少量字段:
const { title } = useRootContext<{ title: Ref<string> }>();
读取多个字段:
interface RootContext {
title: Ref<string>;
increment: () => void;
}
const { title, increment } = useRootContext<RootContext>();
验证可用
检查:
defineRootContext()是否定义在App.vue。App.vue模板中用到的状态是否已从返回值中显式接收。return中是否包含所需共享的状态。- 页面局部状态是否没有误放进根上下文。