To-Do Calendar - Day7 Vuex 狀態管理(上)
當多個組件要共用資料,或者大範圍的組件溝通時,資料的傳遞與維護就會變得相當麻煩,這時候就可以使用 Vuex 來協助我們管理資料狀態。
Vue 的資料傳遞

- 在上下層級時,資料傳遞是使用 emit / props 在做傳遞。
- 在相同層級時,資料傳遞的話可以使用 eventBus,不過 eventBus 僅適合用在簡單的情境。
為什麼不用全域變數來管理?
使用全域變數來管理全部資料,會有失去 Vue 雙向綁定的特性問題。如果是在狀態改變時不需有立即畫面響應變化的情況下,多數會使用 cookie 或 local storage 來存放,但有些情境需要在狀態改變時主動響應來產生畫面互動效果,此時就可以透過 Vuex 來管理這些響應式的資料狀態。
什麼是 Vuex?
- Vuex 是為 Vue.js 應用程序開發的狀態管理模式,可以集中式地儲存管理所有組件的資料,讓各組件共享資料狀態,降低了組件之間溝通的複雜度。
- Vuex 應用的核心就是 store,store 就是存放資料狀態的容器,將各個組件共用的資料放到裡面,進行全域統一管理。
- Vuex 的狀態存儲是響應式的,只要 store 內的資料發生變化,引用該資料的組件頁面也會同步更新。
安裝 Vuex
- 安裝 Vuex
Warning此專案用的是 Vue 2,所以安裝的是對應的 Vuex v3.x 版本。
npm install vuex@3.4.0 --save
- src 下新建 store 目錄,並在裡面新建 index.js
- 在 src/store/index.js 載入
import Vue from "vue"; import Vuex from "vuex"; Vue.use(Vuex); export default new Vuex.Store({ state: { msg: "Hello", }, });
- 在 main.js 中載入
import Vuex from 'vuex' import store from "./store";
- 將 store 加進 Vue
new Vue({ render: (h) => h(App), router, store, }).$mount("#app");
在組件中取得 Vuex 的 state
- 在組件的 computed 中使用 $store.state 來取得資料
<template> <div> <h1>{{msg}}</h1> </div> </template> <script> export default { data() { return {}; }, computed: { msg(){ return this.$store.state.msg; } }, }; </script>
- 運行開發環境,測試 Veux 是否運作
我們已經可以透過 $store.state.msg 取得 state 中的 msg 值了!