返回

从0实现简易版的vuex让你的编程思想更灵活

前端

想要更好的使用一个插件,可以尝试理解其实现的方式。 当然,了解一个优秀的插件,本身也会增强自己的能力。本文,努力从零开始实现一个简易版的vuex,期间会用到很多编程思想,希望自己越来越灵活使用。

简易vuex的实现

准备工作

先可以用vue create xx创建一个项目,不带vuex的。先看看,如果有…

step 1:准备Store类

class Store {
  constructor (options) {
    this._mutations = options.mutations
    this._actions = options.actions
    this._getters = options.getters
    this._state = new Vue({
      data: options.state
    })
  }
}

step 2:封装commit方法

commit(type, payload) {
  const entry = this._mutations[type]
  entry && entry(this.state, payload)
}

step 3:封装dispatch方法

dispatch(type, payload) {
  const entry = this._actions[type]
  entry && entry(this, payload)
}

step 4:封装getters方法

getters(getterName) {
  const entry = this._getters[getterName]
  return entry && entry(this.state)
}

step 5:封装state属性

get state () {
  return this._state.data
}

step 6:创建一个Store实例

const store = new Store({
  state: {
    count: 0
  },
  getters: {
    doubleCount(state) {
      return state.count * 2
    }
  },
  mutations: {
    increment(state) {
      state.count++
    }
  },
  actions: {
    incrementAsync({commit}) {
      setTimeout(() => {
        commit('increment')
      }, 1000)
    }
  }
})

step 7:使用Store实例

new Vue({
  el: '#app',
  store,
  template: `
    <div>
      {{ doubleCount }}
      <button @click="increment">Increment</button>
      <button @click="incrementAsync">Increment Async</button>
    </div>
  `,
  methods: {
    increment() {
      this.$store.commit('increment')
    },
    incrementAsync() {
      this.$store.dispatch('incrementAsync')
    }
  },
  computed: {
    doubleCount() {
      return this.$store.getters.doubleCount
    }
  }
})

结语

以上便是简易vuex的实现。当然,这只是简易版的vuex,并不包含vuex的所有功能。但它可以帮助我们理解vuex的基本原理。希望本文对大家有所帮助。