前置说明
1.Vue2.x 和 Vue3.x区别:
- 在Vue3.x中, 没有辅助函数.
- 其他关于Vuex的使用没有区别.
2. 此处只对于Vuex的几个属性中的使用做扩展补充.
getters补充
当getters写在子模块中时, getters属性中的方法, 全参共有4个参数
getters: {
/**
* 形参说明:
* state: 表示当前模块中的satate
* getters: 表示当前模块中的getters对象, 一般是操作同级的其他方法
* rootState: 表示主模块的satate对象
* rootGetters 表示主模块的getters对象
*
* 主模块也就是-index.js中
*/
getName(state, getters, rootState, rootGetters){
// 使用说明
// state、getters直接调用即可
// rootState.模块名.属性名
// rootGetters['模块名/该子模块下的getters方法名']
// 除了state使用.调用以外, 其他都是用[''],符合命名规范的问题
},
.......
}
actions补充
当actions写在子模块中时, actions中的方法, 第一个形参 context对象中, 会有6个对象(还有别的属性, 只有这6个提供给开发者使用)
定义
// 子模块中的actions
actions: {
/**
* 参数一: context 是一个对象, 如果当前actions定义在子模块中,
* context中会有以下6个提供给开发者使用的对象
*
* 1. commit:调用mutations
* (1).本模块调用:commit('本模块mutations方法名', 实参)
* (2).其它模块调用:commit('模块名/其它模块的mutations方法名', 实参,{root:true}),
* {root:true}固定参数, 表示作为主模块去调用的意思
* 2. state:获取当前模块的state
* 3. dispatch:调用actions方法
* (1).本模块调用:dispatch('本模块的actions方法名', 实参)
* (2).其它模块的调用:dispatch('模块名/其它模块的actions方法名',null,{root:true})
* 4. getters:获取当前模块的getters
* 5. rootState:主模块下的state
* 6. rootGetters:主模块下的getters
*
* 参数二: value是组件中调用时传递的参数
*/
refreshUserName(context, value){
setTimeout(()=>{
store.commit('mutations方法名',实参值)
},2000)
}
}
调用(Vue3.x)
import {useStore} from 'vuex'
setup(){
const store=useStore()
// store===this.$store
store.dispatch('模块名/actions方法名',参数值)
}
开发中, 如果要使用上述6个对象, 都必须通过 context.来获取需要的对象, 可以通过解构, 直接获取
以下是官网的示例:
以上就是Vuex中getters和actions的使用补充说明的详细内容,更多关于Vuex中getters和actions使用补充的资料请关注NICE源码其它相关文章!
