返回

一探Vuex源码深处(五):深入理解state的访问和修改

前端

前言

在Vuex源码分析系列文章的前几部分,我们已经对Vuex的基本原理和使用方式有了深入的了解。在本文中,我们将继续深入Vuex源码,探索state的访问和修改机制。我们将从getters、mutations到actions,层层揭开Vuex内部运作的秘密,帮助您更全面地理解和掌握Vuex的使用。

state的访问

在Vuex中,state是用来存储应用程序状态的全局对象。state可以被组件通过this.store.state访问。当访问到state的时候,会触发Store实例的state的get函数,他会返回this._vm._data.$state。

Object.defineProperty(Store.prototype, 'state', {
  get: function get() {
    return this._vm._data.$state
  }
})

this._vm._data.$$state是一个响应式对象,这意味着当state发生变化时,组件也会相应地更新。

除了通过this.store.state访问state之外,还可以通过getters来访问state。getters是用来获取state的计算属性的函数。getters可以通过this.store.getters访问。

Object.defineProperty(Store.prototype, 'getters', {
  get: function get() {
    if (!this._vm) {
      return {}
    }

    return this._vm._data.$getters || {}
  }
})

getters是通过Vue.extend({})创建的,因此getters也可以像组件一样使用计算属性。

state的修改

在Vuex中,state只能通过mutations来修改。mutations是用来提交更改到state的函数。mutations可以通过this.$store.commit提交。

Object.defineProperty(Store.prototype, 'commit', {
  get: function get() {
    return this._vm._data.$commit
  }
})

mutations是通过Vue.extend({})创建的,因此mutations也可以像组件一样使用methods。

当提交一个mutation时,会触发Store实例的mutation的commit函数,他会依次调用注册在该mutation上的所有函数,并传入mutation的payload。

Store.prototype.commit = function commit(_type, _payload, _options) {
  // check object-style commit
  var mutation = typeof _type === 'object'
    ? _type
    : { type: _type, payload: _payload }
  var entry = this._mutations[mutation.type]

  if (!entry) {
    console.error('[vuex] unknown mutation type: ' + mutation.type)
    return
  }

  this._withCommit(function () {
    entry.forEach(function commitIterator(handler) {
      handler(mutation.payload)
    })
  })

  this._subscribers.forEach(function subscribeIterator(sub) {
    return sub(mutation, this.state)
  })

  if (
    process.env.NODE_ENV !== 'production' &&
    mutation.payload &&
    typeof mutation.payload === 'object'
  ) {
    console.warn('[vuex] `mutation.payload` should be immutable.')
  }
}

总结

在本文中,我们深入分析了Vuex源码,探索了state的访问和修改机制。我们了解了getters、mutations和actions在Vuex中的作用和使用方式。希望这些知识能够帮助您更全面地理解和掌握Vuex的使用。