Vue.js:如何重置动态表单修改内容并控制操作按钮状态
Solution for Per-Item Change Tracking and Revert Functionality
Got it, let's fix this up so each item tracks its own changes independently and can revert properly. Here's the complete working implementation:
<div> <div v-for="(item, key) in items" :key="key"> <div> <input type="text" v-model="item.title" @input="checkItemChange(item)"> </div> <div> <input type="text" v-model="item.description" @input="checkItemChange(item)"> </div> <div class="actions"> <button type="button" @click="discardChanges(item)" :disabled="!item.isChanged">Discard changes</button> <button type="button" @click="sendChanges(item)" :disabled="!item.isChanged">Save</button> </div> </div> </div> <script type="text/javascript"> export default { data() { return { items: [ { title: "Apple", description: "The bigger company of the world" }, { title: "Amazon", description: "The bigger online store of the USA" }, ] } }, created() { // Initialize original values and change state for each item this.items.forEach(item => { item.originalTitle = item.title; item.originalDescription = item.description; item.isChanged = false; }); }, methods: { checkItemChange(item) { // Update change state by comparing current values to original item.isChanged = item.title !== item.originalTitle || item.description !== item.originalDescription; }, sendChanges(item) { // Send API request to update item // Assuming API call succeeds, sync original values to current values item.originalTitle = item.title; item.originalDescription = item.description; item.isChanged = false; }, discardChanges(item) { // Revert to original values and reset change state item.title = item.originalTitle; item.description = item.originalDescription; item.isChanged = false; } } } </script>
Key Changes Explained:
- Per-item state tracking: Instead of a global
itemChangedflag, each item now has its ownisChangedboolean. This ensures buttons only enable/disable for the specific item being modified. - Two-way binding with
v-model: Replaced:valuewithv-modelso user input immediately updates theitemobject — this is critical for detecting changes in real time. - Original value storage: In the
createdhook, we copy each item's initial title/description intooriginalTitle/originalDescription. This gives us a stable reference point to compare against and revert to later. - Change detection: The
checkItemChangemethod runs on every input event, comparing current values to the original ones to update theisChangedstate instantly. - Revert functionality:
discardChangessimply overwrites the current title/description with the original values and resetsisChangedto false. - Save sync: After a successful save (in
sendChanges), we update the original values to match the modified ones, so future changes to that item are detected correctly.
内容的提问来源于stack exchange,提问作者Andreas Hunter
相关产品推荐
相关产品推荐

