我有此代码:
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);
}
}
})
我需要将新添加的值添加到状态。在突变中,它只是作为字符串添加,但是我需要它添加通过输入传递的数字。我将不胜感激。
假设您的问题是items
是字符串而不是数字,请尝试将ADD_BOTTLES
突变更改为
ADD_BOTTLES (state, items) {
let num = parseInt(items, 10)
if (!isNaN(num)) {
state.bottles += items
}
}
[如果要通过表单从用户那里获得值,请考虑使用.number
修饰符。例如(根据您的屏幕截图)...
.number
<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>