vuex提供了一套很方便的辅助函数,用于对$store中的各个对象的成员,如mapState、mapGetters、mapMutations、mapActions,以下为其使用方法
1.mapState
import {mapState} form 'vuex'
export default{
computed:{
//一般写法(自定义方法名)
...mapState({
someState:state => state.someState
}),
//简单写法
...mapState(['someState']),
//等同于
someState(){
return this.$store.state.someState;
}
}
}
2.mapGetters
import { mapGetters } from 'vuex'
export default{
computed:{
//一般写法(自定义方法名)
...mapGetters({
someGetter:'somGetter'
}),
//简单写法
...mapGetters(['someGetter']),
//等同于
someGetter(){
return this.$store.getters.someGetter;
}
}
}
3.mapMutations
import { mapMutations } from 'vuex'
export default{
methods:{
//一般写法(自定义方法名)
...mapMutations({
someMutations:'someMutations'
}),
//简单写法
...mapMutations(['someMutations'])
//等同于
someMutations(){
this.$store.commit('someMutations',...)
}
}
}
4.mapActions
import { mapActions } from 'vuex'
export default{
methods:{
//一般写法(自定义方法名)
...mapActions({
someAction:'someAction'
}),
//简单写法
...mapActions(['someAction']),
//等同于
someAction(){
this.$store.dispatch('someAction',...)
}
}
}
本文仅供想我一样的小白参考,可能还要稍作修改,欢迎大家多多指正