实现简约不简单的vuex
關于vuex的使用,大家自然不陌生,如果有不熟練的可以多看看vuex官網,記住一條原則:異步操作以及復雜的邏輯必須通過action實現,否則會報下列錯誤
Error: [vuex] do not mutate vuex store state outside mutation handlers.
項目源碼遵循原則:vuex對vue具有強依賴,vuex以及本demo只能用于vue項目。
demo拆解:實現state -> commit -> dispatch
- 實現state
tstore.vue文件
實例化一個new TStore,new 實例化會自動包含一個constructor屬性 export default new TStore({state: {count: 1} }) 復制代碼tstore.js文件
import Vue from 'vue'; // 已經說過了,vuex對vue具有強耦,必須引入vueclass TStore {// new 實例化生成的constructor屬性,指向他們的構造函數 constructor 是一種用于創建和初始化class創建的對象的特殊方法constructor(options) { // options就是new Store的實例化 是state這個對象this.state = options.state;new Vue({ data: {state: this.state}});} } 復制代碼index.vue文件
import store from './tstore';computed: {count(){ // 由于暫時沒有實現mapState的方法,只能使用當前return store.state.count;} }, 復制代碼則相當于,在TStore里找到TStore.state,又通過class TStore找到tstore.vue文件中定義的count,則在index.vue里可以使用count
- 實現commit 定義mutations函數
調用commit
store.commit('add')
實現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的實現在源碼里有詳細備注,請大家多多指正。
總結
vuex實現是借用vue本身的數據響應式機制使state相應化,從而使state變化立刻相應在依賴的視圖中。借助vue本身的數據響應式機制進行托管實現單向數據流。原理就是借助了vue的數據劫持,state的值變成響應式,如果state有改變,就通知組件。
上一篇
模仿vue的數據劫持,實現mvvm
轉載于:https://juejin.im/post/5d01ba1af265da1b6836b6df
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的实现简约不简单的vuex的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 收了100元辛苦费,写了一个最简单的C#
- 下一篇: Pulsar集群搭建部署