ianhuang筆記THE ADVENTURER'S JOURNAL
知識世界・持續探索中

ADVENTURE JOURNAL · 探索筆記

Vue 教學 27:Vuex 4 與既有狀態管理維護

任務導覽 TABLE OF CONTENTS

保留 Vuex 的 state、getter、mutation、action 流程,並對照新專案的 Pinia 路線。

適用:Vue 3.5 的單檔元件與 Composition API。先依 第 00 章 建立 Vite 專案;除另有指定,範例取代 src/App.vue。

歷史版本定位

Vuex 4 支援 Vue 3,Vuex 3 常見於 Vue 2。此章使用 Vuex 4.1,是維護舊專案的對照;新專案先參考第 26 章 Pinia。不要直接將 Vuex 的 mapState 套到 Pinia store。

src/store.js:

import { createStore } from 'vuex'
export default createStore({
  state: () => ({ tasks: [] }),
  getters: { count: state => state.tasks.length },
  mutations: { setTasks(state, tasks) { state.tasks = tasks } },
  actions: {
    async load({ commit }) {
      const tasks = await Promise.resolve([{ id: 1, title: 'Vuex 維護練習' }])
      commit('setTasks', tasks)
    }
  }
})

src/main.js:

import { createApp } from 'vue'
import App from './App.vue'
import store from './store.js'
createApp(App).use(store).mount('#app')

App.vue:

<script setup>
import { computed } from 'vue'
import { useStore } from 'vuex'
const store = useStore()
const tasks = computed(() => store.state.tasks)
const count = computed(() => store.getters.count)
</script>
<template>
  <button @click="store.dispatch('load')">讀取</button>
  <ul><li v-for="task in tasks" :key="task.id">{{ task.title }}</li></ul>
  <p>{{ count }} 筆</p>
</template>

讀取後顯示一筆。mutation 保持同步,非同步操作放 action,再以 commit 改資料。此例 Promise 模擬成功回應,正式請求仍需 error/loading。

遷移時比較

Pinia 不要求 mutation,action 可直接改 state;Vuex 的 namespaced modules 對應到多個 Pinia store 時要重看依賴與迴圈引用,而不是只換函式名。先列出每個 action 的輸入、狀態變化與副作用,再逐步切換呼叫端並保留測試。

章節導覽

系列目錄 · 上一章 · 下一章

參考資料

冒險者留言

comments powered by Disqus

搜尋筆記

輸入關鍵字,探索所有筆記。

ESC 關閉 · 搜尋標題、標籤與文章全文