I have this code:
export default new Vuex.Store({
state: {
bottles: 20,
disabledBtn: false
},
mutations: {
REMOVE_BOTTLES(state) {
if (state.bottles > 0) {
state.bottles--;
}
},
ADD_BOTTLES(state, items) {
state.bottles = state.bottles + items
}
},
actions: {
removeOneBottle ({commit}) {
commit('REMOVE_BOTTLES');
},
addBottlesInput ({commit}, items) {
commit('ADD_BOTTLES', items);
}
}
})
I need to add the newly added value to the state. Here in the mutations it is simply added as a string, but I need it to add numbers that passed through the input. I would be grateful for any answer.
Assuming your issue is that items
is a string instead of a number, try changing your ADD_BOTTLES
mutation to
ADD_BOTTLES (state, items) {
let num = parseInt(items, 10)
if (!isNaN(num)) {
state.bottles += items
}
}
If you're getting the value from the user via a form, consider using the .number
modifier. For example (based on your screenshot)...
<template>
<section>
<p>How many bottles are there in total:</p>
<p>{{ bottles }}</p>
</section>
<section>
<p>How many bottles of water were brought?</p>
<input type="number" v-model.number="items" min="0">
<button @click="addBottles(items)">Add</button>
</section>
</template>
import { mapState, mapMutations } from 'vuex'
export default {
data: () => ({ items: 0 }),
computed: mapState(['bottles']),
methods: mapMutations({
addBottles: 'ADD_BOTTLES'
})
}