vuex的4个核心概念 state /getter/mutation/action
state
state(状态树)是用来存储数据的地方
const state = {
name:'张三',
age: 18,
sex: '男'
}
export { state }
组件内部使用:
this.$store.state.name
getter
通过getter在state中派生一些状态(简单的处理) 类似vue的计算属性可以理解为store的计算属性,getter的返回值会很具它的依赖被缓存起来, 只有当它的依赖值发生变化才会被重新计算
const getters = {
someGetter(state, getters){
return state.name + '极客111'
},
someOtherGetter(state, id){
return(id)=>{
return state.height
}
}
}
export {getters}
参数: state(状态) getters(派生状态)
组件内使用:
this.$store.getters.name (会缓存值)
this.$store.getters.fn(id) 通过方法调用,不会缓存结果;
通过方法调用时可以让getter返回一个函数来实现给getter传参
mutation
它可以理解为store的事件,内部是一些改变状态的方法,也是唯一能直接操作state的方法;但是其只支持同步操纵(原因参考官网)
export const mutations = {
increment(state, payload){
state.age += payload.number
},
reduce(state, payload){
state.age--
}
}
参数:[state(状态树), payload(载荷)] 一般payload是个对象
组件内的使用:
this.$store.commit('type', payload) //风格1
this.$store.commit({type:'name', number:2}) //风格2
注意:建议使用常量来替代 mutation 事件类型这样可以使 linter 之类的工具发挥作用,
同时把这些常量放在单独的文件中可以让你的代码合作者对整个 app 包含的 mutation 一目了然
export const SOME_MUTATION = 'SOME_MUTATION' //mutation-types.js
import { SOME_MUTATION } from './mutation-types' //store.js
mutations:{
[SOME_MUTATION](state){...}
}
actions
由于mutation只能处理同步操作,对于异步操作的需求无法满足,因此诞生actions,它也相当于store的事件,和mutation不同的是它是通过提交mutation来改变state的,并不是直接操作的state,它可以处理同步和异步操作
export const actions = {
add(context, payload){
context.commit('increment', payload)
},
reduce(context, payload){
context.commit('reduce')
}
}
参数:
context(和store实例具有相同属性和方法的对象) {state, commit, getters}
payload: 载荷(额外的自定义参数)
组件内使用:
this.$store.dispatch('type', payload)
this.$store.dispatch({type:'name', number:1})
辅助函数
以上不管是哪种属性在组件内调用时都很繁琐,为了简化调用,我们可以使用辅助函数预先进行映射处理;之后再调用就像组件调用自己的属性和方法那样简单
import {mapState, mapGetters, mapMutations, mapActions} from 'vuex' (它是vuex内置的辅助函数)
组件内:
mapState
方式1:箭头函数返回值
computed:mapState({
name : state => state.name,
age : state => state.age,
height : state => state.height
})
方式2:es6的延展性(推荐)
computed:{
...mapState([
'name',
'height',
'age'
])
}
方式3:(结合)可以重命名映射
computed:{
...mapState({
name : state => state.name,
age : state => state.age,
height: state => state.height
})
}
mapGetters
方式1:
computed:{
...mapGetters([
'someGetters',
'someOtherGetters'
])
}
方式2: 可以修改映射命名
computed:{
...mapGetters([
newGetterA : 'someGetters',
newGetterB : 'someOtherGetters'
])
}
mapMutations
方式1:
methods:{
...mapMutations([
'increment',
'reduce'
]),
方式2: 可以重命名映射
...mapMutations({
add : 'increment',
sub : 'reduce'
})
}
mapActions
方式1:
methods:{
...mapActions([
'add',
'reduce'
]),
方式2:可以重命名映射
...mapActions({
action_add: 'add',
action_sub: 'reduce'
})