如何更新Vuex Store状态?账户余额扣除支出功能实现求助
问题描述
我是新手,若表述或代码存在问题请见谅,目前仍在学习中。我尝试多种方式实现账户余额(currentSalar)扣除支出金额(salary)的功能但未成功,二者均为字符串类型而非数字。以下是相关代码,请帮忙解决如何计算并更新Vuex中的currentSalar值:
Vuex 模块代码 (/index.js)
import mutations from './mutations.js'; import actions from './actions.js'; import getters from './getters.js'; export default { namespaced: true, state() { return { registers: [ { id: 'user1', currentSalar: '4,400' , saves: '12,000', currency: '₪', expense: [{salary: '3,000', category: 'Bar:'}] }, { id: 'user2', currentSalar: '100,000', saves: '3,000,000', currency: '$', expense: [] } ] } }, mutations, actions, getters }
Mutations 代码 (/mutations.js)
export default { addRegister(state, payload) { const registerToUpdate = state.registers.find( (register) => register.id === payload.id ); const expenses = registerToUpdate.expense; //////* find((expense) => expense.salary === payload.salary) */ const salary = +expenses.salary; let current = +registerToUpdate.currentSalar; const newCurrnt = current -= salary; // should calculate a new value (UPDATE) for the currentSalar by resting the salary console.log(newCurrnt); expenses.unshift(payload); }, };
Actions 代码 (/actions.js)
export default { addRegister(context, data) { const RegisterData = { id: context.rootGetters.userId, category: data.category, salary: data.salary } context.commit('addRegister', RegisterData); } }
组件代码
<template> <div class="container"> <h1>Add expense</h1> <form @submit.prevent="ReturnCat"> <section> <label for="salary">Amount: </label> <input type="number" id="salary" v-model.number="salary"/> </section> <section> <label for="category">Category: </label> <select id="category" v-model.trim="category"> <option value="Bar: " id="bar"> Bar & Restaurants </option> <option value="Shopping: " id="shopping">Shopping</option> <option value="Needs: " id="needs">Needs</option> </select> </section> <base-button class="btn">ADD</base-button> <h4><a href="">Add entery insted</a></h4> </form> </div> </template> <script> export default { props: ["id"], data() { return { salary: null, category: '', }; }, computed: { expensePath() { return this.$router.replace("/register/" + this.id); }, }, methods: { ReturnCat() { const form = { salary: this.salary, category: this.category } this.$store.dispatch('register/addRegister', form); console.log(this.salary, this.category); }, } }; </script> <style scoped> #salary { margin: 1rem auto auto 1rem; height: 1.5rem; width: 11rem; } select, option { margin: 1rem auto 2rem 1rem; height: 1.5rem; width: 11rem; } .btn { margin: 0 auto; width: 11rem; } </style>
解决方案
核心问题是带千分位逗号的字符串无法直接转为数字,同时mutations里的取值逻辑有误,修正步骤如下:
1. 添加数值格式转换工具函数
在 mutations.js 开头新增两个工具函数,处理字符串和数字的格式转换:
// 移除字符串中的逗号并转为数字 const strToNum = (str) => { if (!str) return 0; return Number(str.replace(/,/g, '')); }; // 将数字转为带千分位逗号的字符串 const numToStr = (num) => { return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); };
2. 修正 mutations 中的计算与更新逻辑
修改 addRegister 方法,用工具函数处理数值,并正确更新账户余额:
export default { addRegister(state, payload) { const registerToUpdate = state.registers.find( (register) => register.id === payload.id ); // 组件传过来的salary是数字,直接使用 const expenseAmount = payload.salary; // 将带逗号的余额字符串转为数字 const currentBalance = strToNum(registerToUpdate.currentSalar); // 计算新余额并转回带逗号的字符串格式 const newBalance = currentBalance - expenseAmount; registerToUpdate.currentSalar = numToStr(newBalance); // 将支出金额转为带逗号的字符串后,添加到expense数组 registerToUpdate.expense.unshift({ ...payload, salary: numToStr(expenseAmount) }); }, };
3. 组件表单提交优化(可选)
确保表单能正确触发提交事件,给自定义的base-button添加type="submit"属性(需确认组件支持传递该属性):
<base-button class="btn" type="submit">ADD</base-button>
这样就能实现账户余额扣除支出金额,并正确更新Vuex中的currentSalar值。
内容的提问来源于stack exchange,提问作者Jaime Uriel Kasabe
相关产品推荐
相关产品推荐

