如何将新增加的值添加到跨突变的状态?

问题描述 投票:0回答:1

我有此代码:

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);
  }
 }
})

我需要将新添加的值添加到状态。在突变中,它只是作为字符串添加,但是我需要它添加通过输入传递的数字。我将不胜感激。

javascript vue.js vuex
1个回答
0
投票

假设您的问题是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>
© www.soinside.com 2019 - 2024. All rights reserved.