← 返回完整题库
vue.js中等

Pinia 有哪些使用场景?

参考答案

定义

Pinia 是 Vue 官方推荐的下一代状态管理库(Vue 3 默认,Vue 2 配合 composition-api),模型是「一个 store = 带 state/getters/actions 的响应式模块」,没有 mutation、没有嵌套 modules。

适用场景

  1. 跨页面共享的业务状态:用户信息与登录态、权限角色、购物车、全局配置(主题/语言/时区)。
  2. 多步流程:下单向导的地址、支付方式、优惠券跨步骤共享。
  3. 缓存型数据:字典、机构树、城市列表这类「一次拉取、多方复用」的数据 + 失效控制。
  4. 全局 UI 状态:侧边栏展开、当前 tab、页面级 loading 计数、弹窗队列。
  5. 协同状态:画布编辑器的选中节点、缩放、撤销栈。
  6. SSR 状态注入:服务端预取写入 store,序列化到页面,客户端复用以免二次请求。
  7. 持久化:配合 pinia-plugin-persistedstate 把部分 state 写 localStorage。

不适合

只在父子间传的数据、只读常量、单页表单草稿、超大且频繁变化的列表渲染数据(放 store 会扩大订阅面)。

export const useCartStore = defineStore('cart', () => {
  const items = ref([])
  const total = computed(() => items.value.reduce((s, i) => s + i.price * i.qty, 0))
  function add(item) { items.value.push(item) }
  return { items, total, add }
})

按业务域拆 store,store 之间用 useXxxStore() 组合,避免互相 import 内部 state。

本题来自 计算机知识面试题库,共 921 道题。