docs/archives/102-web-architecture-refactor/experience.md
Web架构重构过程中积累的核心经验,包括Vue Composable架构设计、响应式系统优化和依赖注入最佳实践。
在异步回调中调用Vue Composable函数会导致错误:Uncaught (in promise) SyntaxError: Must be called at the top of a 'setup' function。这违反了Vue Composition API的核心规则,需要重构架构。
// ❌ 错误:在异步回调中调用Composable
onMounted(async () => {
const services = await initServices();
const modelManager = useModelManager(); // 错误:不在setup顶层调用
});
// ✅ 正确:顶层声明,响应式连接
const { services } = useAppInitializer(); // 在顶层调用
const modelManager = useModelManager(services); // 在顶层调用,传入services引用
// 内部实现:响应式连接
export function useModelManager(services: Ref<AppServices | null>) {
// 状态定义...
// 响应式连接:监听服务就绪
watch(services, (newServices) => {
if (!newServices) return;
// 使用已就绪的服务...
}, { immediate: true });
return { /* 返回状态和方法 */ };
}
AppServices接口,统一管理所有核心服务useAppInitializer负责创建和初始化所有服务services引用作为参数<script setup>顶层同步调用watch监听服务就绪,而不是在回调中调用Composablereactive vs ref 的深度实践为解决 Vue 深层嵌套 ref 无法自动解包的问题,我们将多个核心 Composables 的返回值从包含多个 ref 的对象,重构为了单一的 reactive 对象。
inject 获取服务实例Cannot read properties of null (reading 'value') 错误reactive 对象属性与期望 ref 的接口不匹配toRef 作为适配器
// 为 reactive 对象的属性创建一个双向绑定的 ref
const selectedTemplateRef = toRef(optimizer, 'selectedTemplate');
Content-Type 响应头reactive 适用于管理一组相关状态,简化顶层 APIref 依然是跨组件传递单个响应式变量的可靠方式toRef 和 toRefs 是在 reactive 和 ref 之间适配的必备工具<script setup>顶层同步调用watch监听服务就绪,保持代码清晰和可维护reactive和ref各有适用场景,toRef是重要的适配工具文档类型: 经验总结
适用范围: Vue Composable架构开发
最后更新: 2025-07-01