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 的类型推断,使代码更加类型安全。
const counterStore = useCounterStore()
const currentCount = counterStore.count
const doubleCount = counterStore.doubleCount