actions、getters
actions:处理异步操作
需求:一秒钟之后,修改 state 的 count 成 200
说明:mutations 必须是同步的(便于监测数据变化,记录调试)
actions 本质上不是直接修改 state 的数据,因为要修改 state 必须要经过 mutations,所以就算想要处理异步,也是在 actions 中把异步处理完了,然后在里面去用 mutations,actions 相当于帮我们把异步给包装处理掉了
actions 使用步骤:
1. 提供 actions 方法:
actions : {
setAsyncCount (context, num) { // context:上下文,若未分模块,可以理解为 store 仓库。若分模块,默认提交的就是自己模块;num:参数
setTimeout ( () => { // 这里是 setTimeout 模拟异步,以后大部分场景是发请求(发请求也是异步)
context.commit ( ' changeCount ' , num) // 提交 mutations :context.commit ( ' mutations 中方法名字 ' , 参数 )
} , 1000)
}
}
2. 页面中 dispatch 调用:
this.$store.dispatch ( ' setAsyncCount ' , 200)
--------------------------------------------------------------------------------------------------------------------------
getters:(类似于计算属性)
除了 state 之外,有时我们还需要从 state 中 派生出一些状态,这些状态是依赖 state 的,此时会用到 getters
场景:state 仓库中有一个 list 数组:[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ],如果直接用 {{ $store.state.list }} 展示,会展示出整个 list,但我只想展示出大于 5 的数。
getters使用:(getters 也是响应式的)
1. 定义 getters(getters 中的函数的第一个参数是 state,分模块后该 state 指的是子模块的 state;getters 中的函数必须要有返回值)
getters : {
filterList (state) {
return state.list.filter (item => item > 5)
}
}
2. 访问 getters
① 通过 store 访问 getters
eg:{{ $store.getters.filterList }} // filterList:getters 中的函数名
② 通过辅助函数 mapGetters 映射
 
                    
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号