Search code examples
vuejs2bootstrap-vue

Vue.js2 v-for separate protperties


With the code below, if I press the "Edit" button, I change the disabled state all the rows, how can I separate this? I mean, once i just want to edit one row.

        cols="12"
        class="contact-container"
        v-for="contact in contacts"
        :key="contact.id"
      >
        <b-form inline>
          <b-input
            type="text"
            :value="contact.name"
            :disabled="editMode ? disabled : ''"
          />
          <b-input
            type="tel"
            :value="contact.phoneNumber"
            :disabled="editMode ? disabled : ''"
          />
          <b-input
            type="email"
            :value="contact.email"
            :disabled="editMode ? disabled : ''"
          />
          <b-input
            type="text"
            :value="contact.title"
            :disabled="editMode ? disabled : ''"
          />
          <b-button-group>
            <button type="button" size="lg" class="btn">
              <b-icon-x-circle-fill variant="danger"></b-icon-x-circle-fill>
            </button>
            <button type="button" size="lg" class="btn" @click="startEdit">
              <b-icon-pencil-fill variant="primary"></b-icon-pencil-fill>
            </button>
          </b-button-group>

Solution

  • Assuming that editMode is part of the components' data. If it's a prop this solution might be a bit tricky to implement.

    Set up editMode as an empty object in your component's data. And for the method startEdit it should take, as a parameter, the id of the contact being edited.

    So something like this: @click="startEdit(contact.id)". and in the method body, this.$set(this.editMode, contact.id, true). See Reactivity in Depth in Vue docs for information on this.$set.

    To check if a row is disabled use :disabled="editMode[contact.id]" (no need for ternary operator checking as it's a boolean)

    This approach will make it possible to edit multiple rows at the same time. Though a name such as editedContacts might be better in this case.