vuex實(shí)現(xiàn)

index.js

import Vue from 'vue'
import Vuex from './kvuex'

// 實(shí)現(xiàn)一個(gè)插件:$store掛載
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    add(state) {
      // state怎么來的
      state.count++
    }
  },
  getters: {
    doubleCount: state => {
      return state.count * 2;
    }
  },
  actions: {
    asyncAdd({commit}) {
      setTimeout(() => {
        commit('add')
      }, 1000);
    }
  },
  modules: {
  }
})

vuex.js

// 1.實(shí)現(xiàn)一個(gè)插件:實(shí)現(xiàn)Store,掛載$store
// 引用Vue構(gòu)造函數(shù)
let Vue;

class Store {
  constructor(options){
    // 只要放到data上,即成為響應(yīng)式的數(shù)據(jù)
    // vm.data.count  vm.count
    this._vm = new Vue({
      data: {
        $$state: options.state
      }
    })
    
    // 保存mutaions
    this._mutations = options.mutations;

    this._actions = options.actions;

    // 綁定commit、dispatch方法中的this到Store實(shí)例上
    const store = this;
    const {commit, dispatch} = store;
    this.commit = function boundCommit(type, payload) {
      commit.call(store, type, payload)
    }
    this.dispatch = function boundDispatch(type, payload) {
      dispatch.call(store, type, payload)
    }
  }

  // 只讀state,可以獲取數(shù)據(jù)
  get state() {
    return this._vm._data.$$state
  }

  set state(v) {
    console.error('表改,這里不能修改state,想改請(qǐng)使用replaceState()');
    
  }

  // commit: type-mutation類型,payload-參數(shù)
  commit(type, payload) {
    const entry = this._mutations[type]
    if (!entry) {
      console.error('unknown mutation type:'+type);
      return
    }
    // 在這可以做一些攔截處理

    // 傳遞state進(jìn)去
    entry(this.state, payload)
  }

  // action: type-action類型,payload-參數(shù)
  dispatch(type, payload) {
    const entry = this._actions[type]
    if (!entry) {
      console.error('unknown mutation type:'+type);
      return
    }
    // 在這可以做一些攔截處理
    
    // 傳遞上下文進(jìn)去,實(shí)際上就是Store實(shí)例
    entry(this, payload)
  }
}

function install(_Vue) {
  Vue = _Vue

  // 全局混入
  Vue.mixin({
    beforeCreate() {
      if (this.$options.store) {
        Vue.prototype.$store = this.$options.store
      }
    }
  })
}

// 下面導(dǎo)出的對(duì)象等同于Vuex,實(shí)例化時(shí)使用new Vuex.Store
export default {Store,install}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容