当前位置: 首页 > news >正文

Vuex 和 Pinia 的区别

API 设计

  • ​​Vuex​​:API 设计基于选项式 API,需要定义 state、mutations、actions 和 getters 等选项。
const store = new Vuex.Store({state: {count: 0},mutations: {increment(state) {state.count++}},actions: {asyncIncrement({ commit }) {setTimeout(() => {commit('increment')}, 1000)}},getters: {doubleCount(state) {return state.count * 2}}
})
  • ​​Pinia​​:基于组合式 API,使用 defineStore 定义 store,代码更加简洁直观。
import { defineStore } from 'pinia'export const useCounterStore = defineStore('counter', {state: () => ({count: 0}),actions: {increment() {this.count++},async incrementAsync() {await new Promise(resolve => setTimeout(resolve, 1000))this.count++}},getters: {doubleCount: (state) => state.count * 2}
})

状态修改

  • Vuex​​:状态修改必须通过 mutations 提交同步修改,异步操作在 actions 中提交 mutations。
// 在组件中使用
this.$store.commit('increment') // 同步修改
this.$store.dispatch('asyncIncrement') // 异步修改
  • Pinia​​:支持在 actions 中直接修改 state,也支持异步操作。
// 在组件中使用
const counterStore = useCounterStore()
counterStore.increment() // 直接修改状态
counterStore.incrementAsync() // 异步修改状态

类型支持

  • ​​Vuex​​:Vuex 4 对 TypeScript 有一定的支持,但类型推断相对较弱,需要手动进行一些类型声明。
  • ​​Pinia​​:专为 TypeScript 设计,具有更强大的类型推导支持,能充分利用 Vue 3 的 Composition API 的类型推断,使代码更加类型安全。
// 在 Pinia 中,TypeScript 可以自动推断出状态和获取器的类型
const counterStore = useCounterStore()
const currentCount = counterStore.count // 类型为 number
const doubleCount = counterStore.doubleCount // 类型为 number

相关文章:

  • 【版本控制】SVN + TortoiseSVN版本管理实用教程(附安装+开发常用操作)
  • C语言基础语法详解:从入门到掌握
  • Object.defineProperty 与 Proxy解析
  • Python Cookbook-6.9 快速复制对象
  • 为什么vue的key值,不用index?
  • 文件传输过滤器绕过:Exe2Hex
  • 【资料推荐】LVDS Owner’s Manual
  • pcd2pgm的launch文件实现
  • [C]基础13.深入理解指针(5)
  • 第18章:MCP在创作领域中的应用
  • 表示学习与部分域适应
  • 第19章:Multi-Agent多智能体系统介绍
  • “IAmMusicFont.com“:将音乐变成视觉
  • 14.ArkUI Radio的介绍和使用
  • CSS Position 属性完全指南
  • 高精度运算
  • 【多目标进化算法】 MOEA/D算法(知识点)
  • PH热榜 | 2025-04-25
  • [Windows] 电脑清理加速:Windows Cleaner v5.0.5
  • ORB-SLAM3核心模块、数据结构和线程交互方面解析
  • 为何不当教练转型高校管理岗?苏炳添曾吐露过真实的想法
  • 公安部知识产权犯罪侦查局:侦破盗录传播春节档院线电影刑案25起
  • “养老规划师”实则售卖保险,媒体:多部门须合力整治乱象
  • 加拿大财长:加拿大需要抗击美国关税
  • 人民日报:外卖平台应保障好骑手就业权益,消除后顾之忧
  • 荣盛发展:拟以酒店、代建等轻资产板块业务搭建平台,并以其股权实施债务重组