[Vuejs]-How do I access an element inside a v-for loop?

0👍

Instead of trying to access the inputs in your handler, you could use a temporary variable in each array element to automatically store the corresponding input value, and then copy them over when you’re ready to save in modifyList():

  1. Define saveTemp() to save the user’s input in a temporary variable (e.g., __temp) within the current array element (item):

    saveTemp(item, key, value) {
      item.__temp = item.__temp || {};
      item.__temp[key] = value;
    }
    
  2. Add <input> change-event handlers that call saveTemp() to store the input value in the current array element (t):

    <td><input @change="saveTemp(t, 'name', $event.target.value)" :value="t.name"></td>
    <td><input @change="saveTemp(t, 'phone', $event.target.value)" :value="t.phone"></td>
    <td><input @change="saveTemp(t, 'email', $event.target.value)" :value="t.email"></td>
    <td><input @change="saveTemp(t, 'address', $event.target.value)" :value="t.address"></td>
    
  3. Update the SAVE button’s click-handler to pass the array element (t) instead of index to modifyList():

    <img v-b-tooltip.hover.bottom="'save'" v-on:click="modifyList(t)">
    
  4. Update modifyList() to check for __temp data to be committed, using Object.assign():

    modifyList(item) {
      if (!item.disabled && item.__temp) {
        Object.assign(item, item.__temp);
        delete item.__temp;
      }
    },
    

demo

👤tony19

Leave a comment