Vuex vs Pinia 差異比較
比較 Vuex 和 Pinia 的核心差異,包含 API 設計、TypeScript 支援、模組化方式等,並提供遷移指南。
1. 面試回答主軸
- 核心差異:Vuex 需要 mutations,Pinia 不需要;Pinia 有更好的 TypeScript 支援;模組化方式不同。
- 選擇建議:Vue 3 新專案推薦 Pinia,Vue 2 專案使用 Vuex。
- 遷移考量:從 Vuex 遷移到 Pinia 的步驟與注意事項。
2. 核心差異總覽
| 特性 | Vuex | Pinia |
|---|---|---|
| Vue 版本 | Vue 2 | Vue 3 |
| API 複雜度 | 較複雜(需要 mutations) | 更簡潔(不需要 mutations) |
| TypeScript 支援 | 需要額外配置 | 原生完整支援 |
| 模組化 | 嵌套模組 | 扁平化,每個 store 獨立 |
| 體積 | 較大 | 更小(約 1KB) |
| 開發體驗 | 良好 | 更好(HMR、Devtools) |
3. API 差異比較
3.1 Mutations vs Actions
Vuex:需要 mutations 來同步修改 state
// Vuex
export default createStore({
state: { count: 0 },
mutations: {
INCREMENT(state) {
state.count++;
},
},
actions: {
increment({ commit }) {
commit('INCREMENT');
},
},
});
Pinia:不需要 mutations,直接在 actions 中修改 state
// Pinia
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
increment() {
this.count++; // 直接修改
},
},
});