Vuex mapMutations
VueX mapMutations: is used simply to replace this.$store.commit('abc') to mapMutations(['abc','..']). its functionalities are the same but mapMutations is more preferable and useful as it is able to combine different functions in mutations into one.
Example:
App.vue
simple.js
mapMutation calls deductPrice handler function in mutations properties like
One more note here is that we could not call mapMutations with payload injected.
To overcome the issues raised above, we can do like this:
Note: mutations handler function must be synchronous otherwise, it is impossible to track those functions inside mutation logs.
Final result:
Example:
App.vue
<template>
<div id="app">
<Counter />
</div>
</template>
<script>
import {store, Counter } from './state/simple'
export default {
name: 'app',
store,
components: {
Counter
},
data () {
return {
placeHolder: 'Focus on me'
}
},
}
</script>
simple.js
import Vue from 'vue';
import Vuex, { mapGetters, mapMutations } from 'vuex';
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
products:[
{id:1,name:'pizza', price:10},
{id:2, name:'fan', price: 20},
{id:3, name:'headset', price:30 },
{id:4,name: 'phone', price: 1004}
]
},
mutations: {
deductPrice( state ) {
return state.products.map(item => item.price -= 1)
}
},
getters:{
getBigPrice (state) {
return state.products.filter(item => item.price >= 10)
},
getCountItem ( state, getters ) {
return getters.getBigPrice.length
}
},
actions:{
}
})
const Counter = {
template: `<div> Total {{ itemCount }}
<li v-for="product in products"> Id:{{ product.id }},
name:{{ product.name }}, Price:{{ product.price }} </li><br/>
<button @click="deductPrice">Deduct</button>
</div>`,
computed:{
...mapGetters(
{ products: 'getBigPrice',
itemCount: 'getCountItem'}
)
},
methods:{
...mapMutations(['deductPrice'])
}
}
export {store, Counter }
mapMutation calls deductPrice handler function in mutations properties like
methods:{
...mapMutations(['deductPrice'])
}
One more note here is that we could not call mapMutations with payload injected.
To overcome the issues raised above, we can do like this:
mutations: {
deductPrice( state ) {
return state.products.map(item => item.price -= 1)
}
}
Note: mutations handler function must be synchronous otherwise, it is impossible to track those functions inside mutation logs.
Final result:
Comments
Post a Comment