實現簡約不簡單的vuex

關於vuex的使用,你們天然不陌生,若是有不熟練的能夠多看看vuex官網記住一條原則:異步操做以及複雜的邏輯必須經過action實現,不然會報下列錯誤html

Error: [vuex] do not mutate vuex store state outside mutation handlers.vue

項目源碼

遵循原則:vuex對vue具備強依賴,vuex以及本demo只能用於vue項目。
demo拆解:實現state -> commit -> dispatchgit

  • 實現state

tstore.vue文件github

實例化一個new TStore,new 實例化會自動包含一個constructor屬性
export default new TStore({
  state: {
    count: 1
  }
})
複製代碼

tstore.js文件vuex

import Vue from 'vue';  // 已經說過了,vuex對vue具備強耦,必須引入vue

class TStore {
  // new 實例化生成的constructor屬性,指向他們的構造函數  constructor 是一種用於建立和初始化class建立的對象的特殊方法
  constructor(options) {  // options就是new Store的實例化 是state這個對象
    this.state = options.state;
    new Vue({ 
      data: {
        state: this.state
      }
    });
  }
}
複製代碼

index.vue文件redux

import store from './tstore';

computed: {
  count(){  // 因爲暫時沒有實現mapState的方法,只能使用當前
    return store.state.count;
  }
},
複製代碼

則至關於,在TStore裏找到TStore.state,又經過class TStore找到tstore.vue文件中定義的count,則在index.vue裏能夠使用countbash

  • 實現commit 定義mutations函數
mutations: {
    add(state) {
      state.count++;
    }
  },
複製代碼

調用commit
store.commit('add')app

實現vuex異步

import Vue from 'vue';

class TStore {
 constructor(options) {  // options就是new Store的實例化
   this.state = options.state;
   this.mutations = options.mutations;
   new Vue({  // vuex對於vue有強耦,只能用於vue redux則不是
     data: {
       state: this.state
     }
   });
 }

 commit(type, payload) {  // 此時type就是add,就是調用commit時傳的參
   // this.mutations是定義的mutations函數,則this.mutations.app則是add這個函數,傳入type參數便可實現
   const mutation = this.mutations[type];   // 拿到函數 執行
   mutation(this.state, payload); // 傳參給mutation 也就是this.mutations函數
 }
}
複製代碼

action的實如今源碼裏有詳細備註,請你們多多指正。mvvm

總結

vuex實現是借用vue自己的數據響應式機制使state相應化,從而使state變化馬上相應在依賴的視圖中。藉助vue自己的數據響應式機制進行託管實現單向數據流。原理就是藉助了vue的數據劫持,state的值變成響應式,若是state有改變,就通知組件。

上一篇
模仿vue的數據劫持,實現mvvm

相關文章
相關標籤/搜索