前端学习笔记-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 都开放。
相关推荐
Csvn10 小时前
WASM
前端
修己xj11 小时前
我用 AI 给自己写了一个 Markdown 编辑器,然后把它开源了
前端
FRing0311 小时前
vue2干货总结2(v-bind、v-for、v-model、指令修饰符、v-bind操作class和style)
开发语言·前端·vue.js·vue2
幸运小猿12 小时前
模拟慢上传-处理超时重试image 丢失线上问题
前端·javascript·html
视觉小萌新12 小时前
AI Class 3 · Chapter 1:变量、字符串、list/dict、if/for(python学习-小白版-有经验可跳过)
python·学习·list
moshuying13 小时前
网购能买Token了!
前端
h_654321013 小时前
echarts实现柱状图加一条横线
前端·echarts
风骏时光牛马13 小时前
生成一个后端标题,只需要一个标题,不需要其他的任何文本。
前端
子非鱼@Itfuture13 小时前
关于前后端联调中登录状态/登录信息失效?
java·前端
郭小李13 小时前
openFeign入门
java·开发语言·前端