Vue 3 中階

Pinia 與 Vuex 差異?

AI 練習作答

概述

Pinia 是 Vue 3 官方推薦的狀態管理庫,是 Vuex 的現代繼任者

語法比較

Vuex(繁瑣)

// store/counter.js(Vuex)
export default {
  state: () => ({ count: 0 }),
  mutations: {
    increment(state) { state.count++ }
  },
  actions: {
    async incrementAsync({ commit }) {
      await delay(1000)
      commit('increment')
    }
  },
  getters: {
    doubled: state => state.count * 2
  }
}

// 使用
store.commit('increment')       // mutation
store.dispatch('incrementAsync') // action
store.getters.doubled           // getter

Pinia(簡潔)

// stores/counter.js(Pinia)
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  const doubled = computed(() => count.value * 2)

  function increment() { count.value++ }
  async function incrementAsync() {
    await delay(1000)
    increment()
  }

  return { count, doubled, increment, incrementAsync }
})

// 使用
const counter = useCounterStore()
counter.increment()        // 直接呼叫
counter.incrementAsync()   // 非同步也一樣
counter.doubled            // getter 也是 computed

主要差異

特性 Vuex Pinia
Vue 版本 Vue 2 / 3 主要針對 Vue 3
Mutations ✅ 必須 ❌ 直接修改 state
TypeScript 一般 ✅ 一流支援
DevTools
模組化 巢狀 modules 多個獨立 store
語法 繁瑣 簡潔(類似 Composition API)
Bundle 大小 較大 較小(~1KB)

推薦

Vue 3 新專案一律推薦使用 Pinia,Vuex 4 僅用於維護舊專案。

✦ AI 模擬面試

輸入你的答案,AI 即時分析精準度與改進空間

登入後即可使用 AI 評分