面試官:說下 vuex 實現原理?
Vuex 是 Vue.js 專用的狀態管理模式和庫,統一管理應用的全局狀態,解決組件之間的數據共享問題。其本質原理是利用 Vue 提供的響應式系統,配合 Vue 的數據響應機制實現數據驅動視圖更新。
一、Vuex 設計核心(五大核心模塊)
Vuex主要包括如下幾個模塊:
模塊 | 功能 | 是否響應式 |
State | 存儲全局狀態的數據對象 | ? |
Getters | 對 State 數據進行加工處理,類似組件內的 computed 計算屬性 | ? |
Mutations | 同步修改 State 數據的唯一方法,觸發響應式更新 | ?(只是觸發更新,不必響應式) |
Actions | 提交 Mutations,可以包含異步邏輯 | ? |
Modules | 分模塊管理狀態,方便擴展與維護 | ? |
二、vuex 的實現原理(詳細拆解)
① Vue 響應式基礎
Vuex 最根本的原理是基于 Vue 本身的數據響應系統:
- 通過 new Vue() 或 Vue.observable 方法: 將 state 對象定義為 Vue 實例的 data 屬性或通過 Vue.observable 變成響應式。
// 簡單的響應式 state 實現示例
let state = Vue.observable({ count: 0 });
- 當 state 數據變化時,任何使用 state 數據的組件都會自動響應式更新。
② 核心實現——store 對象
- store 是一個單例對象,整個應用僅有一個。
- store 實例包含 State、Getters、Mutations、Actions 等成員。
核心示意代碼:
class Store {
constructor(options) {
this._vm = new Vue({
data: {
$$state: options.state
}
});
this.getters = {};
Object.keys(options.getters || {}).forEach(getterName => {
Object.defineProperty(this.getters, getterName, {
get: () => options.getters[getterName](this.state)
});
});
this.mutations = options.mutations || {};
this.actions = options.actions || {};
}
// 提供 state 訪問方式
get state() {
return this._vm._data.$$state;
}
// mutation必須同步執行
commit = (type, payload) => {
const mutation = this.mutations[type];
if (mutation) mutation(this.state, payload);
else console.error(`[vuex] unknown mutation type: ${type}`);
};
// action 可以異步
dispatch = (type, payload) => {
const action = this.actions[type];
if (action) return action(this, payload);
else console.error(`[vuex] unknown action type: ${type}`);
};
}
③ Vuex 的輔助函數(輔助方法)
- 輔助函數 mapState、mapGetters、mapMutations、mapActions,方便組件使用 store 中的數據與方法。
示例:
// vue組件內使用vuex的輔助函數示例
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex';
export default {
computed: {
...mapState(['count']),
...mapGetters(['doubleCount'])
},
methods: {
...mapMutations(['increment']),
...mapActions(['incrementAsync'])
}
};
④ 嚴格模式(strict mode)
嚴格模式下,只能通過 mutation 修改 state,防止不規范的 state 修改行為:
const store = new Vuex.Store({
strict: true
});
嚴格模式原理是使用 Vue 提供的 watch API 監聽 state 變化,判斷 state 變化是否是 mutation 導致的。如果不是,會給出警告。
三、vuex 流程示意圖(核心實現流程圖示)
Vue組件
│
dispatch (異步) → Actions ──commit──→ Mutations
│ │
└─────────→ commit (同步) ←───┘
│修改
▼
State (響應式對象)
│
▼
通知組件更新
四、vuex 常見的面試追問點:
面試官追問 | 推薦回答 |
state是如何實現響應式的? | 基于Vue自身的響應式系統:使用Vue.observable或Vue實例實現 |
為什么只能通過mutation修改state? | 保證所有的狀態修改有跡可循,便于追蹤變化、調試與維護 |
為什么actions允許異步而mutations不允許異步? | 因為mutation必須是可預測、可追蹤的同步修改狀態,異步邏輯統一封裝在actions中,更好維護 |
什么時候用 getters? | 當store數據需要做復雜計算或多組件共享計算邏輯時 |
五、總結:Vuex 實現原理的核心思想
- Vuex 實質是利用 Vue 的響應式系統。
- 統一狀態數據到單例 store 中,提供明確、規范的狀態修改方式(Mutation 同步、Action 異步)。
- 通過嚴格模式、輔助方法確保開發規范,提供良好開發體驗。