對 Vuex 源碼進行濃縮,DIY 一個小型 Vuex
功能如下
- 通過
$store.commit
改變$store.state
- 實現 strict model
源碼約70行左右比較好理解,下面講解一下兩個比較重要的點。
install
Vue.use(Vuex)
實際上調用的是 Vuex 的 install
方法,該方法在每個組件的 beforeCreate
鉤子中爲當前組件注入 $store
,使所有組件的 $store
屬性都指向同一個對象,也就是創建 Vue 實例時傳入的 store
對象。
監聽 store
爲什麼當 state 對象發生變化時視圖會被更新?原因是 store 內部創建了一個 Vue 對象對 state 進行監聽(見源碼 resetStoreVM
方法)。而且上面也提到,使用 Vuex 後,所有組件的 $store
都引用的都是同一個 store。所以當 state 變化時,綁定了 state 的視圖都會更新。