Search code examples
javascriptvue.jsvue-componentvuetify.js

Deleting row in Vuetify data table always removes the last row


I'm trying to implement deleting of individual rows from table. Each row has a delete icon that opens a confirm dialog when clicked. If the user clicks the "Yes" button, that specific row should be deleted.

However, the issue is that no matter what row I click, the last row of table is always deleted.

Here is my code:

// table
<v-data-table
   :headers="headers"
   :items="tableData"
   :search="search"
>
   <template v-slot:item.actions="{ item }">
      <div class="table__icons">
        <v-icon
           small
           class="mr-2"
           @click="goToContract(item)"
        >
          mdi-pencil
        </v-icon>
        <a v-if="$route.name === 'pregled-ugovora' || $route.name === 'pregled-znsa'" :href="ispisRow(item)"
           target="_blank">
           <v-icon
             small
           >
             mdi-download
           </v-icon>
          </a>
          <v-icon
              v-if="$route.name === 'pregled-znsa'"
              small
              @click="openDeleteModal(item)"
          >
            mdi-delete
          </v-icon>
          <v-icon v-if="$route.name === 'pregled-ugovora'"
                  small
                  @click="getIzvjestaj(item)"
          >
            mdi-note-text
          </v-icon>
        </div>
      </template>
</v-data-table>

// delete dialog
<v-dialog v-model="dialogDelete" max-width="500px">
  <v-card>
    <v-card-title class="text-h2 delete-text">Do you want to remove this row?</v-card-title>
    <v-card-actions>
      <v-spacer></v-spacer>
      <div class="m-btn delete-btn" @click="closeDeleteModal">No</div>
      <div class="m-btn delete-btn" @click="deleteZnsConfirm">Yes</div>
      <v-spacer></v-spacer>
    </v-card-actions>
  </v-card>
</v-dialog> 

// methods
openDeleteModal(item) {
   this.deletedZnsIndex = this.tableData.indexOf(item)
   this.deletedZns = Object.assign({}, item)
   this.dialogDelete = true
},
closeDeleteModal(item) {
   this.deletedZnsIndex = ''
   this.deletedZns = {}
   this.dialogDelete = false
},
deleteZnsConfirm(item) {
   this.tableData.splice(this.tableData.indexOf(this.deletedZns), 1)
   this.dialogDelete = false
},

Solution

  • Oh I figured it out...

    Instead of this:

    deleteZnsConfirm(item) {
       this.tableData.splice(this.tableData.indexOf(this.deletedZns), 1)
       this.dialogDelete = false
    },
    

    My delete function should look like this:

    deleteZnsConfirm(item) {
       this.tableData.splice(this.deletedZnsIndex, 1)
       this.dialogDelete = false
    },
    

    I was using the wrong index while splicing tableData :(