前端学习笔记-vue状态管理优化

15 扁平化你的 Store,合理使用持久化

一句话理解

Store(Pinia / Vuex)里的数据结构要像数据库表一样扁平 (用 id 做关联,别深层嵌套);持久化(存 localStorage)要有选择,别什么都存。

为什么

  • 深层嵌套的 Store → 更新困难、响应式开销大(呼应第 07 条)。比如要改"文章 5 的评论 3 的点赞数",深层路径又慢又容易写错。
  • 扁平化(normalized) → 用 { [id]: item } 的 map 结构,查找 O(1),更新精准。
  • 持久化全存 → localStorage 有容量限制(5MB 左右),存太多会卡、还会存进敏感数据。

代码示例

反例:嵌套 + 全量持久化:

js 复制代码
// 嵌套结构:改一个评论的点赞数要穿透 3 层
const badStore = {
  posts: [
    {
      id: 1,
      title: '...',
      comments: [
        { id: 10, likes: 5, author: { id: 7, name: '张三' } }
      ]
    }
  ]
}

正例:扁平化(像数据库表):

js 复制代码
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useForumStore = defineStore('forum', () => {
  // 三张"表",用 id 关联,互不嵌套
  const posts = ref({})           // { [postId]: post }
  const comments = ref({})        // { [commentId]: comment }
  const users = ref({})           // { [userId]: user }

  // O(1) 查找某篇文章
  const getPost = (id) => posts.value[id]

  // 精准更新某条评论的点赞数,不影响其它数据
  const likeComment = (commentId) => {
    comments.value[commentId].likes++
  }

  return { posts, comments, users, getPost, likeComment }
})

有选择地持久化(只存该存的):

js 复制代码
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  const token = ref('')        // 持久化:登录态
  const profile = ref({})      // 持久化:用户资料

  const tempCaptcha = ref('')  // 不持久化:临时验证码
  const formDraft = ref({})    // 不持久化:表单草稿

  // 手动持久化关键数据(或用 pinia-plugin-persistedstate 按需配置)
  function persist() {
    localStorage.setItem('token', token.value)
  }

  return { token, profile, tempCaptcha, formDraft, persist }
})
</script>

新人提示

  • 扁平化的核心思想:数据按"实体"分表,用 id 互相引用,和后端数据库设计同源。
  • 持久化的判断:"刷新页面后还需要吗?" 需要(如登录态)→ 存;不需要(如临时状态)→ 不存。
  • 别持久化敏感数据(密码、密钥)到 localStorage,它对任何 JS 都开放。
相关推荐
子兮曰2 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰2 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
一隅论数智2 天前
给AI一张“业务概念地图“:本体如何从哲学走向企业智能
大数据·人工智能·经验分享·笔记·学习·学习方法·政务
XiHongShi20162 天前
STM32F407 RTC定时器例程,建议保存
stm32·单片机·学习
前端小万2 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝2 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
三十而立洋2 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
爱吃苹果的日记本2 天前
离散数学第六课
学习·离散数学
卡布鲁2 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js