vuex

vuex中actions中函数默认自带参数context,为什么

2020-12-17  本文已影响0人  cheesepear

context的话就相当于state的父亲,上一级,包含着state中的所有属性

context:{

state, 等同于store.$state,若在模块中则为局部状态

rootState, 等同于store.$state,只存在模块中

commit, 等同于store.$commit

dispatch, 等同于store.$dispatch

getters 等同于store.$getters

}

常规写法调用的时候会使用context.commit,但更多的是使用es6的变量解构赋值,也就是直接在参数的

位置写自己想要的属性,如:{commit}。

例如:

prev ({dispatch, state}) {

const list = state.listInfo.songList

if (state.listInfo.songIndex === 0) {

state.listInfo.songIndex = list.length

} else {

state.listInfo.songIndex--

}

const hash = list[state.listInfo.songIndex] && list[state.listInfo.songIndex].hash

dispatch('getSong', hash)

},

dispatch:含有异步操作;而commit只是同步操作,都是提交 mutation,因为只能在mutation中才能够改变state中的值,然而mutation中只能进行同步操作,从而actions就出现了,actions允许异步和同步操作,但是对于actions的操作其实就是提交mutation来完成

来源:vuex中actions中函数默认自带参数context,为什么还可以写成{commit}或者{dispatch}或者其他的_单人�的博客-CSDN博客

上一篇 下一篇

猜你喜欢

热点阅读