Vue表格输入框无法更新数组address字段问题排查及优化方案咨询
The core issue here is that your input uses one-way binding with :value="location.address", which means changes to the input don't update your editedAddress variable. When you click "Edit", you set editedAddress to the original address, but as you type in the input, editedAddress stays stuck at that original value. So when you click "Update", you're just reassigning the same old address back to location.address—hence no visible change.
Quick Fix for Your Current Setup
Modify the input element to update editedAddress in real-time as the user types. Replace your existing input with this:
<input type="text" :value="location.disabled ? location.address : editedAddress" :disabled="location.disabled" @input="editedAddress = $event.target.value">
This does two key things:
- When the input is disabled (not editing), it displays the original
location.address - When enabled (editing), it uses
editedAddressas the value and updates it whenever the user types
Your existing btnUpdate method will now work correctly because editedAddress will hold the new value when you click Update.
⚠️ Note: This approach uses a single editedAddress variable, so if you click Edit on another row without saving, you'll lose the unsaved changes from the first row.
Robust Solution (Per-Row Edit State)
For a cleaner, more maintainable approach, track edit state individually for each location. This avoids losing unsaved changes when switching between rows and scales better if you add more editable fields later.
Step 1: Update Your Data Structure
Add a tempAddress field to each location to store the edited value temporarily:
data(){ return{ locations:[ { address:'Mall of lahore', disabled: true, tempAddress: '' }, { address: 'The Post Office', disabled: true, tempAddress: '' }, { address: 'Mall of Dubai', disabled: true, tempAddress: '' } ], address: '' } },
Step 2: Modify the Edit Method
When clicking Edit, populate the temporary address field with the current value:
btnEdit(index){ this.locations[index].disabled = false; // Copy current address to temp storage for editing this.locations[index].tempAddress = this.locations[index].address; },
Step 3: Update the Input Element
Bind the input to the temporary address when editing:
<input type="text" :value="location.disabled ? location.address : location.tempAddress" :disabled="location.disabled" @input="location.tempAddress = $event.target.value">
Step 4: Adjust the Update Method
Save the temporary address to the permanent address field and disable editing:
btnUpdate(index){ this.locations[index].address = this.locations[index].tempAddress; this.locations[index].disabled = true; },
This approach keeps each row's edit state isolated, so switching between rows won't lose unsaved changes. It also makes your code more organized and easier to extend.
内容的提问来源于stack exchange,提问作者Muhammad Ameen Sheikh

