vuex的actions返回结果类型是promise及actions方法互相调用

this.$store.dispatch(‘logout’)返回的结果是Promise类型的
在这里插入图片描述
调用成功的情况下,返回状态为fulfilled,值为undefined。
所以可以直接进行.then操作:

this.$store.dispatch('logout').then((result) => {
  console.log(result);
});

因为 Vuex 的 action 是设计为可以处理异步操作的,并且当你调用 dispatch 方法时,它会返回一个表示该操作完成的 Promise。

拓展:

1.其余的store.getters、store.commit是同步的,则不返回promise。
2.在actions中可以通过dispatch调用actions中其他的方法
  actions: {
    resetToken ({ dispatch }) {
      dispatch('logout').then(() => {
        console.log("...");
      })
    },
    logout ({ commit }) {
      localStorage.removeItem('token')
      localStorage.removeItem('role')
      commit('setToken', '')
      commit('setRole', '')
    }
  },

在Vuex中,actions中的函数传递的第一个参数是一个包含以下属性的上下文对象(context)

a.state:当前模块的局部状态对象。
b.rootState:整个Vuex的根状态对象。
c.commit:用于提交mutation的方法。
d.dispatch:用于分发action的方法。
e.getters:当前模块的局部getters对象。
f.rootGetters:整个Vuex的根getters对象。

使用解构赋值将其中需要的结构出来。

第二个参数是载荷,即传给Vuex的数据。

mutations函数接收两个参数:
a.state:当前模块的局部状态对象。
b.payload:可选的参数,用于传递额外的数据。

  • 9
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值