如何通过Vuex Store更新现有数据对象且不覆盖原有状态?
Hey there! I see exactly what's going on here—your current Vuex mutation is replacing the entire userToSave state object every time you call it, which is why your second dispatch wipes out the existing user data. Let's fix this step by step.
The Root Problem
Your updateUser mutation uses direct assignment:
state.userToSave = user
This means every commit throws away the old userToSave object and replaces it with the new user parameter. So when you pass just this.designID (a single value or small object) the second time, it overwrites all previous user data entirely.
Solution 1: Update the Mutation to Merge Objects
Instead of replacing the whole object, we'll merge the new data into the existing state. You can use the object spread operator (cleaner syntax) or Object.assign() for this:
const mutations = { updateUser(state, user) { console.log("Mutation User:", user); // Merge existing user data with new incoming data // New properties override old ones; new keys get added state.userToSave = { ...state.userToSave, ...user }; // Alternative with Object.assign (same end result): // state.userToSave = Object.assign({}, state.userToSave, user); } }
How this works:
- The spread operator
...takes all key-value pairs fromstate.userToSaveand spreads them into a new object. - We then spread the key-value pairs from the incoming
userparameter into the same new object. - If the incoming
userhas a key that already exists instate.userToSave, the new value overwrites the old one. If it's a new key, it gets added to the object. - This preserves all existing user data while adding/updating the new properties you need.
Solution 2: Fix the Second Dispatch Call
One important detail: if this.designID is a raw value (like a string or number), passing it directly as user will break the merge. You need to wrap it in an object to create a valid key-value pair:
afterPick(){ this.closeModalDesign = false; this.$store.dispatch({ type: "updateCurrentUser", user: { designID: this.designID } // Wrap the value in an object with the correct key }) this.paymentInit = true; },
Without this, you'd be trying to merge a non-object value into your user object, which would corrupt the state structure. Always pass an object with the specific keys you want to update.
Quick Vuex Note
Remember: all state modifications in Vuex must happen inside mutations (you're already doing this correctly!). Merging with a new object (via spread or Object.assign()) helps Vue detect state changes and keep your components reactive. You could also modify individual properties directly (e.g., state.userToSave.designID = user.designID), but merging is more flexible if you ever need to update multiple properties at once.
内容的提问来源于stack exchange,提问作者Profit23

