欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > Vuex 和 Pinia 的区别

Vuex 和 Pinia 的区别

2025/4/26 22:26:14 来源:https://blog.csdn.net/weixin_49078296/article/details/147516973  浏览:    关键词: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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词