Vuex源码分析(五)-- actions

本文详细分析了Vuex中actions的官方描述及其源码实现,包括构造函数store、installModule和makeLocalContext等关键部分。actions与mutations的区别在于actions允许包含异步操作,并通过dispatch进行调用。在源码中,actions的处理涉及到参数传递、模块安装和上下文封装,使得actions能够灵活处理复杂业务逻辑。
摘要由CSDN通过智能技术生成

官方描述

Action 类似于mutation,不同在于:

  • Action 提交的是 mutation,而不是直接变更状态。
  • Action 可以包含任意异步操作。

让我们来注册一个简单的 action:

const store = new Vuex.Store({
   
  state: {
   
    count: 0
  },
  mutations: {
   
    increment (state) {
   
      state.count++
    }
  },
  actions: {
   
  	// context = {dispatch, commit, getters, state, rootGetters, rootState}
    increment (context) {
   
      context.commit('increment')
    }
  }
})

从这里可以看出,context有6个属性分别是dispatch, commit, getters, state, rootGetters, rootState。你也许会觉得奇怪,为什么gettersstate有各自的root信息,而dispatchcommit没有?

因为:dispatch, commit 是方法,可以通过传递参数指向对应的root方法,即store.dispatch(type, payload, {root: true});而gettersstate是属性,不能传参,所以重新引入了rootGetters, rootState属性

源码分析

构造函数store

mutations一样,核心方法都在 installModule 方法中。

export class Store {
   
  constructor (options = {
   }) {
   
    ...
    // 生成state模型
    this._modules = new ModuleCollection(options)
    const state = this._modules.root.state

    // 处理[state, getters, mutations, actions]的核心方法
    installModule(this, state, [], this._modules.root)
    ...
  }
}

installModule

这段代码主要是将原始 actions 对象封装到store上

function installModule (store, rootState, path, module, hot) {
   
  const namespace = store._modules.getNamespace(path)

  // 生成本地local对象
  const local = module.context = makeLocalContext(store
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值