Menu
CoddyTech

设置 Store 结构

本课属于 Coddy Vue 学习旅程的“路由与状态”单元。第 36 课,共 55 课。

设置型 store 使用 ref 表示其状态,使用 computed 值表示其 getter,并使用函数表示其 action。返回这些成员,让 Pinia 能够跟踪并公开它们。这种风格使用了你已经熟悉的 Composition API 工具。

export const useTimerStore=defineStore('timer',()=>{
 const minutes=ref(5);
 const seconds=computed(()=>minutes.value*60);
 function extend(){minutes.value++}
 return {minutes,seconds,extend};
});

在 setup 函数内部,ref 仍然使用 .value。在外部,响应式 store 会自动解包它们。请返回所有状态属性,不要隐藏 store 的私有状态;Pinia 需要返回这些成员来管理状态。普通的临时组件草稿仍然可以保留在 store 外部。

challenge icon

挑战

中等

实现 setup 风格的 usePlanStore。声明 seats ref,初始值为 1;声明 room ref,初始值为 Small;再声明一个 computed 标签 room: seats,以及一个 add 操作。让该存储返回所有状态 ref、computed 值和操作。提供的房间切换功能和连续点击 add 都必须更新两个显示值。

保留提供的路由显示和引导文件。

亲手试试

<!doctype html><html><head><meta charset="UTF-8"><title>Routing practice</title></head><body><div id="app"></div><script type="module" src="./main.js"></script></body></html>
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

路由与状态中的所有课