Getting the id of a row from a v-data-table in VueJs

I am currently facing an issue with retrieving the id of a specific field from each row. I require this id as a parameter for a function that will be utilized in an action button to delete the row. Here is how my table template appears:

       <template v-slot:top>
            <v-toolbar flat>
              <v-toolbar-title>Publications</v-toolbar-title>
              <v-divider class="mx-4" inset vertical> </v-divider>
              <v-text-field
                v-model="search"
                append-icon="mdi-magnify"
                label="Search"
                single-line
                clearable
                class="shrink"
                hide-details=""
              ></v-text-field>
              <v-divider class="mx-4" inset vertical> </v-divider>
              <v-btn
                color="orange"
                v-on:click="
                  changeRoute();
                  showEditDialog = true;
                "
                v-show="showAddBtn"
                >{{ txtAddNew }}
              </v-btn>
            </v-toolbar>
          </template>
          <template v-slot:[`item.actions`]>
            <v-btn color="primary" fab x-small elevation="2">
              <v-icon>edit</v-icon>
            </v-btn>

            <v-btn
              v-on:click="deletePublication()"
              color="primary"
              fab
              x-small
              elevation="2"
            >
              <v-icon>delete_forever</v-icon>
            </v-btn>
          </template>
        </v-data-table>
      </template>

This is how my headers appear (multiple headers are loaded dynamically) :

    headers: [],
    headersInitial: [
      {
        text: "Publication ID",
        value: "ID",
      },
      {
        text: "Publication Type",
        value: "publicationType",
      },
      {
        text: "Publication Name",
        value: "titlePublication",
      },

      {
        text: "Publication Year",
        value: "year",
      },
      {
        text: "Actions",
        value: "actions",
        sortable: false,
      },
    ],
    headersWithoutPubTypes: [
      {
        text: "Publication ID",
        value: "ID",
      },
      {
        text: "Publication Name",
        value: "titlePublication",
      },

      {
        text: "Publication Year",
        value: "year",
      },
      {
        text: "Actions",
        value: "actions",
        sortable: false,
      },
    ],
    publications: [],
    filteredPublications: [],

This is how I populate my table with data:

initialize() {
      this.headers = this.headersInitial;
      axios.get("https://localhost:44349/api/items/GetPublications").then((pubData) => {
        this.publications = pubData.data;
        this.filteredPublications = pubData.data
      });
    },

Below is my delete function:

deletePublication() {
      let ID =  this.headersInitial.ID
      if (confirm('Are you sure you want to delete the record?')) {
        axios.get("https://localhost:44349/api/items/DeleteItem/" + ID).then((response) => {
        this.publications = response.data;
        this.filteredPublications = response.data
        });
      }
    },

When attempting to delete a record, I encounter this error: "Uncaught (in promise) Error: Request failed with status code 400". How can I resolve this?

Answer №1

const rowID = this.headersInitial.ID

this.headersInitial is actually an array, so it does not have a property called ID

In order for your deletePublication() method to work properly, it should accept the ID of the row as a parameter, since it may be called with different IDs each time

To achieve this, Vuetify provides the actual row as a prop using the item slot. Replace v-slot:item.actions with

v-slot:item.actions="{ item }"
as demonstrated in the example. The item represents the current row object and can be used in your handler like
v-on:click="deletePublication(item.ID)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the Relationship Between jQuery and JSON through Iterating Over JSON Arrays

There is an array stored in a database: a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";} To manipulate this array, I first unserialize it using PHP and then encode it with JSON. The code snippet is as follows: $unwp = unserialize(&apos ...

What is the correct way to execute the query "select * from table where indexA >= 'a' order by indexB ASC limit 10" in indexedDB?

As I delve into learning about javascript IndexedDB, I have encountered a challenge in executing complex queries. My goal is to perform a select query like this one: "select * from table where indexA >= 'a' order by indexB ASC limit 10" I a ...

Direct users to a different page upon reloading the page in Django

Currently working on a web application with the Django framework. In one of the forms in my app, I am looking to automatically redirect to a new page upon reloading the current page, rather than when the form is submitted. Any insights from the community w ...

Transform the words in a string into an array

I'm scratching my head trying to find a solution on Stack Overflow, but nothing seems like the right fit. Can anyone provide some guidance? I need a regex that will enable me to use JavaScript split to break a string into an array. The test case is: ...

What is the best way to apply focus to a list element using Javascript?

I recently created code to display a list of elements on my webpage. Additionally, I implemented JavaScript functionality to slice the elements. Initially, my page displays 5 elements and each time a user clicks on the "show more" link, an additional 5 ele ...

What is preventing me from integrating angular-cookies into my application?

I'm struggling to resolve this issue where I can't seem to make it work. My aim is to integrate NgCookies (angular-cookies) into my application, but all I'm encountering are errors. This is what I currently have: JS files being included: ...

Converting keyValue format into an Array in Angular using Typescript

Is there a way to change the key-value pair format into an array? I have received data in the following format and need to convert it into an array within a .TS file. countryNew: { IN: 159201 BD: 82500 PK: 14237 UA: 486 RU: 9825 } This needs to be transf ...

submit the JSON formatted data to the server

I am attempting to extract data from a form and transmit it to a remote server: Below is the code snippet: <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js"></script> </head> ...

Issue encountered with the openpgpjs example: `'The function openpgp.encrypt is not defined'`

I encountered an issue with the 'openpgp.encrypt is not a function' error while attempting to follow the sample provided on the openpgp.js github page: https://github.com/openpgpjs/openpgpjs/blob/master/README.md#getting-started After following ...

Clicking on React Js reverses an array that had previously been unreversed

My issue involves an array pulled from a database that I have reversed so that the newest entry is displayed at the top when a button is clicked, opening a modal-style window. However, when the array is displayed in the modal window, it appears to be flipp ...

Merging two arrays of objects from the same response in JavaScript

How can I efficiently merge two arrays of objects from the same response? let data = [{ "testLevel":"mid", "testId":"m-001", "majorCourse": [ { "courseName":"C++" ...

Converting Large XLSX File (over 600MB) to CSV Using Node.js

Currently, I am facing an issue with converting a large XLSX file, which is over 600mb in size, to CSV format. The conversion process works perfectly fine with smaller files that are less than 3MB. However, when it comes to larger files, the program star ...

When executing a JavaScript program, an error with the message 'MODULE_NOT_FOUND' appeared, causing the internal module loader in Node to throw an error at line 1145

node:internal/modules/cjs/loader:1145 throw err; ^ Error: Module 'C:\Users\sande\3D Objects\JavaScript-Lesson\lesson08.js' not found at Module._resolveFilename (node:internal/modules/cjs/loader:1142:15) at Mo ...

The static files are being received by Django but are not functioning properly

I've been working on a project using django 1.7, and below is my settings.py configuration: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "assets"), ) STATIC_ROOT = "absolute/path/to/static" In the 'assets&apo ...

Preventing file overwriting using fs.writefile method

Encountering an issue where the data being saved from a chat room built with socket.io in nodejs is constantly overwritten upon submission of a message. The desired outcome is to append both the username and message to the JSON file as an object, rather th ...

Effortlessly move events to a different calendar using the tab menu feature in FullCalendar

My issue involves having multiple calendars within a tab container that can be switched using a navigation menu. I want to be able to drag events between these calendars using the navigation menu, but I encounter an error where if I switch tabs while dragg ...

What methods could I use to prevent the WYSIWYG buttons from automatically linking?

I've been working on creating an editor but I'm facing a small issue. Every time I click on a button (such as bold or italic), it follows a link instead of performing the desired action. Here's a snippet of what I've tried so far: fu ...

Ways to refresh a canvas element without requiring a full page reload

My goal is to restart a canvas on a website without reloading the page, making the restart dynamic. However, I've noticed that after multiple restarts, the animation slows down and memory usage increases. The situation is complicated by my use of Met ...

Using Npm to install a module results in an abundance of files being provided

Back when I used npm install 6 months ago to install a module, it would create a new folder under node_modules containing all the files for that module. However, now when I use it, it creates multiple files for one module. How can I install a module to a ...

I am seeking to showcase an image in a window, and upon the image being clicked, execute the code in a separate window

I am looking to showcase the image provided below. <img src="http://gfx.myview.com/MyView/skins/livesample/image/livesample.gif" alt="" border="0"><a/> Once the image is clicked, I want it to execute the following code. How can I ensure that ...