從 Vuex 1.x 升上 2.0,有些觀念需要重新對齊。以下把應用結構、模組化、插件與嚴格模式這幾塊整理成一份可直接查閱的知識庫。
Vuex 對你的目錄結構其實毫無意見,它約束的是原則:
1. 應用層級的狀態集中在 store 中。
2. 改變狀態的唯一途徑是提交 mutation,而 mutation 必須是同步事務。
3. 異步邏輯一律封裝在 action 裡。
守住這三條,其餘怎麼擺放是你的自由。store 檔案太大時,把它拆成 action、mutation、getter 幾個檔即可。稍複雜一點的應用則需要 module,一個典型的骨架如下:
├── index.html
├── main.js
├── api
│ └── ... # 在這裡發 API 請求
├── components
│ ├── App.vue
│ └── ...
└── store
├── index.js # 組合 modules 並 export store
├── actions.js # 根層級 action
├── mutations.js # 根層級 mutations
└── modules
├── cart.js # 購物車模組
└── products.js # 商品模組
更完整的示範可參考官方文件中的購物車範例。
單一狀態樹意味著所有狀態都在同一個大物件裡,應用一長大,store 就腫得難看。Vuex 因此允許你把 store 切成多個 module,每個 module 各自擁有 state、mutation、action、getter,甚至可以嵌套:
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const store = new Vuex.Store({
modules: { a: moduleA, b: moduleB }
})
store.state.a // -> moduleA 的 state
store.state.b // -> moduleB 的 statemodule 的 mutation 與 getter,第一個參數收到的是該模組的本地 state:
const moduleA = {
state: { count: 0 },
mutations: {
increment: (state) => {
// 這裡的 state 是模組本地狀態
state.count++
}
},
getters: {
doubleCount (state) {
return state.count * 2
}
}
}action 裡則是 context.state 對應本地狀態,context.rootState 才是根狀態:
const moduleA = {
// ...
actions: {
incrementIfOdd ({ state, commit }) {
if (state.count % 2 === 1) {
commit('increment')
}
}
}
}getter 的第三個參數會把根狀態暴露出來:
const moduleA = {
// ...
getters: {
sumWithRootCount (state, getters, rootState) {
return state.count + rootState.count
}
}
}要特別注意:module 內的 action、mutation 與 getter 依然註冊在全域命名空間中,這代表多個模組可能同時響應同一個 mutation 型別。避免碰撞的做法是在名稱上加前綴或後綴——如果你的 Vuex 模組是可重複使用、執行環境未知,就該這麼做。以 todos 模組為例:
// types.js
// 為 getter、action 與 mutation 定義常數名稱,並加上 todos 前綴
export const DONE_COUNT = 'todos/DONE_COUNT'
export const FETCH_ALL = 'todos/FETCH_ALL'
export const TOGGLE_DONE = 'todos/TOGGLE_DONE'
// modules/todos.js
import * as types from '../types'
const todosModule = {
state: { todos: [] },
getters: {
[types.DONE_COUNT] (state) { /* ... */ }
},
actions: {
[types.FETCH_ALL] (context, payload) { /* ... */ }
},
mutations: {
[types.TOGGLE_DONE] (state, payload) { /* ... */ }
}
}store 建立之後,可以用 registerModule 追加模組:
store.registerModule('myModule', {
// ...
})該模組的狀態會暴露在 store.state.myModule。其他 Vue 插件也能為既有的 store 附加模組,再透過動態註冊取得 Vuex 的狀態管理能力。例如 vuex-router-sync 就是在動態註冊的模組中管理路由狀態,把 vue-router 與 vuex 整合起來。
相對地,store.unregisterModule(moduleName) 可以移除動態註冊的模組,但無法移除建立 store 時就宣告的靜態模組。
store 接受 plugins 選項,它把每一次 mutation 的鉤子暴露出來。一個 Vuex 插件其實就是一個只接收 store 的函式:
const myPlugin = store => {
// store 初始化完成時呼叫
store.subscribe((mutation, state) => {
// 每次 mutation 之後呼叫,格式為 { type, payload }
})
}
const store = new Vuex.Store({
// ...
plugins: [myPlugin]
})插件不能直接改狀態——這點和元件一樣,只能透過 mutation 觸發變化。因此插件很適合用來把外部資料源同步進 store,例如把 websocket 的訊息灌進來:
export default function createWebSocketPlugin (socket) {
return store => {
socket.on('data', data => {
store.commit('receiveData', data)
})
store.subscribe(mutation => {
if (mutation.type === 'UPDATE_DATA') {
socket.emit('update', mutation.payload)
}
})
}
}
const plugin = createWebSocketPlugin(socket)
const store = new Vuex.Store({ state, mutations, plugins: [plugin] })有些插件需要取得狀態快照,比對 mutation 前後的差異。這 requires 深拷貝:
const myPluginWithSnapshot = store => {
let prevState = _.cloneDeep(store.state)
store.subscribe((mutation, state) => {
let nextState = _.cloneDeep(state)
// 比對 prevState 與 nextState ...
// 存起來給下一次 mutation 用
prevState = nextState
})
}這類插件只適合開發階段使用,交給建置工具判斷環境:
const store = new Vuex.Store({
// ...
plugins: process.env.NODE_ENV !== 'production' ? [myPluginWithSnapshot] : []
})插件預設是啟用的。要上 production,得用 Webpack 的 DefinePlugin 或 Browserify 的 envify,把 process.env.NODE_ENV !== 'production' 轉成 false。
如果你已經在用 vue-devtools,這個就不需要了。
Vuex 附帶一個通用除錯用的日誌插件:
import createLogger from 'vuex/dist/logger'
const store = new Vuex.Store({
plugins: [createLogger()]
})createLogger 支援幾個設定:
const logger = createLogger({
collapsed: false, // 是否自動展開 mutation 紀錄
transformer (state) { // 記錄前轉換 state,例如只留子樹
return state.subTree
},
mutationTransformer (mutation) { // mutation 格式為 { type, payload }
return mutation.type // 可依需求自訂格式
}
})它也可以透過 <script> 標籤直接引入,此時會提供全域的 createVuexLogger 方法。同樣地,logger 會產生狀態快照,只在開發環境使用。
啟用方式很簡單,建立 store 時傳入 strict: true:
const store = new Vuex.Store({
// ...
strict: true
})嚴格模式下,只要狀態在 mutation 之外被修改就會拋出錯誤,確保所有變更都能被除錯工具明確追蹤。
開發環境與正式環境要分開:不要在 production 開啟嚴格模式。它會深度監聽整個狀態樹來偵測非法修改,效能開銷不小。同樣交給建置工具處理:
const store = new Vuex.Store({
// ...
strict: process.env.NODE_ENV !== 'production'
})https://vuex.vuejs.org/en/plugins.html
https://vuex.vuejs.org/en/strict.html
https://vuex.vuejs.org/en/modules.html
https://vuex.vuejs.org/en/structure.html
以上就是這次整理的內容,希望能幫上正在把專案升到 Vuex 2.0 的朋友。