defineRootContext
在根部视图声明跨页面共享上下文
defineRootContext() 用于在根部视图中定义跨页面共享的状态与方法。
它的核心价值是给“全局共享能力”一个稳定的落点,并在页面切换时保持同一份上下文。
使用位置
src/App.vue的<script setup>顶层
src/App.vue
<script setup lang="ts">
const ctx = defineRootContext(() => {
return {
// user, token, logout, openGlobalModal...
};
});
</script>
defineRootContext() 只允许在 App.vue 中使用。页面、布局与组件通过 useRootContext() 读取。签名
defineRootContext<T>(factory: () => T): T
参数
factory
- 类型:
() => T - 含义:上下文工厂函数,返回一组需要跨页面共享的状态/方法
返回值
返回 factory 的返回值 T。
src/App.vue
<script setup lang="ts">
const { count, increment } = defineRootContext(() => {
const count = ref(0);
const increment = () => {
count.value += 1;
};
return { count, increment };
});
</script>
<template>
<view @click="increment">{{ count }}</view>
</template>
类型
推荐在 App.vue 中声明并导出上下文类型,再传给 defineRootContext<T>():
src/App.vue
<script setup lang="ts">
export interface RootContext {
title: Ref<string>;
increment: () => void;
}
defineRootContext<RootContext>(() => {
// ...
});
</script>
类型从 App.vue 导出后,页面里的 useRootContext() 无需再手写泛型。
约束与建议
- 只放“跨页面共享”的内容:登录态、全局开关、全局弹窗控制等。
- 不要把单页局部状态放进来,避免耦合与维护成本。
- 返回值建议是由
ref/computed/函数等组成的 plain object。