说白了mapState,mapGetters,mapMutations,mapActions 其实就是对state,gettters,mutations,actions的重命名而已。
1.mapState
他是对state的对象进行二次计算,他可以简化我们代码,这样我们获取cartList,不用写this.$store.state.cartList一大串了,尤其对于我们组件中用到次数挺多的情况下,我们完全可以用mapState来代替。
import { mapState } from 'vuex'
export default {
computed:mapState({
cartList:state => state.cartList,
//或者我们新定义一个参数,接受cartList,这样组件其他地方用到了,我们可以用this.getCartList
//来获取
getCartList:'cartList'
})
}
2.mapGetters
我们可以理解成他是和mapState一样,都是对state里面的参数进行计算,并返回相应的值,所以我们平常看到的mapState.mapGetters都是在computed属性里面,但是和mapState有点不同的是,mapState是仅对state里面的参数进行计算并返回,而mapGetters是对state参数派生出的属性进行计算缓存,比如计算state中cartList数组的长度或者对他的参数进行筛选
import { mapGetters} from 'vuex'
//getters.js
export default {
getCartListLen: state =>{
return state.cartList.length
}
}
//组件
export default {
computed:{
mapGetters({
getLen:'getCartListLen'
}),
}
}
getLen 是对getCartListLen的重命名,如果我们将state里面所有的值都映射到getters里面,那么我们可以写成
import { mapGetters} from 'vuex'
export default {
computed:{
...mapGetters(['getCartListLen','getCartList']),
}
}
如果只是用到state里面部分参数,但是参数的个数超过一个,并且该参数都是在同一个对象下面,如
//state.js
export default {
cartInfos:{
total_price:0, //商品总价
total_amount:0, //商品的数量
}
}
在我们组件中我们如果同时需要获取total_price,total_amount,并且我们想要一起写在mapState里面,那我们可以这样写
import { createNamespacedHelpers } from 'vuex'
const { mapGetters } = createNamespacedHelpers ('cartInfos')
...mapGetters({
choosePrices:'getTotalPrice'
}),
3.mapMutations
mapMutations是写在methods里面,因为他触发的是方法
import { mapMutations} from 'vuex'
export default {
methods:{
...mapMutations([
'add_cart', // 将 `this.add_cart()` 映射为 `this.$store.commit('add_cart')`
]),
}
}
4.mapActions
import { mapActions} from 'vuex'
export default {
methods:{
...mapActions([
'add_cart', // 将 `this.add_cart()` 映射为 `this.$store.dispatch('add_cart')`
]),
}
}