1.mapState
他是对 state 的对象进行二次计算,他可以简化代码,这样我们就可以获取 cartList,不用写 this.$store.state.cartList 一大串了,尤其对于我们组件中用到次数挺多的情况下,我们完全可以用 mapState 来替代。
import { mapState } from 'vuex'
export default {
computed: mapState({
carList: 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')`
])
}
}