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

我有这个代码:


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

  }

 }

})

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


米琪卡哇伊
浏览 93回答 1
1回答

呼唤远方

假设您的问题是items字符串而不是数字,请尝试将您的ADD_BOTTLES突变更改为ADD_BOTTLES (state, items) {&nbsp; let num = parseInt(items, 10)&nbsp; if (!isNaN(num)) {&nbsp; &nbsp; state.bottles += items&nbsp; }}如果您通过表单从用户那里获取值,请考虑使用.number修饰符。例如(根据您的屏幕截图)...<template>&nbsp; <section>&nbsp; &nbsp; <p>How many bottles are there in total:</p>&nbsp; &nbsp; <p>{{ bottles }}</p>&nbsp; </section>&nbsp; <section>&nbsp; &nbsp; <p>How many bottles of water were brought?</p>&nbsp; &nbsp; <input type="number" v-model.number="items" min="0">&nbsp; &nbsp; <button @click="addBottles(items)">Add</button>&nbsp; </section></template>import { mapState, mapMutations } from 'vuex'export default {&nbsp; data: () => ({ items: 0 }),&nbsp; computed: mapState(['bottles']),&nbsp; methods: mapMutations({&nbsp; &nbsp; addBottles: 'ADD_BOTTLES'&nbsp; })}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript