I am looking to customize the v-data-table in Vuetify by adding a tbody section and incorporating additional components in every row

Recently, I have been exploring the usage of v-data-table within the Vuetify.js framework. While v-data-table has proven to be quite beneficial in handling data, I encountered some challenges when attempting to integrate additional components. Despite my efforts, my initial experiment did not yield the desired outcome. Specifically, I attempted to incorporate a v-btn within each row, only to encounter an error message during the process.

If anyone has any advice or suggestions on how to successfully add buttons and textfields to v-data-tables, your input would be greatly appreciated.

    <template>
    <div>
        <v-data-table
         dense
         :headers="header"
         :items="items"
         class="elevation-1"
         >
         <template v-slot:body="{ items}">
             <tbody>
                 <tr v-for="item in items" :key="item.email">
                     <td>{{item.name}}</td>
                     <td>{{item.email}}</td>
                     <td><v-btn @click="deleteRow(item)">delete</v-btn></td>
                 </tr>
             </tbody>
         </template>
        </v-data-table>
    </div>
</template>

<script lang="ts">
import {Component, Vue} from 'nuxt-property-decorator'
import axios from 'axios'

@Component({})
export default class extends Vue{
    header = [
        {text:'name',value:'name'},
        {text:'email',value:'email'},
        {text:'Actions',value:'actions',sortable:false}
    ]
    items:any=[]
    deleteRow(index:any){
       let item=this.items.findIndex((it:any)=>it.email===item.email)
        this.items.splice(index,1);
    }
    async mounted(){
        const response = await axios.get('https://jsonplaceholder.typicode.com/users');
        this.items = response.data.map((item:any)=>({
            name:item.name,
            email:item.email
        }));
    }
    
}
</script>

[error message]

TypeError: Cannot read property 'email' of undefined at eval (axiostest4.vue?eedd:35) ....

Answer №1

Attempt using the following syntax:

<template v-slot:item.actions="{ item }">
to access the current item or row

 <v-data-table
         dense
         :headers="header"
         :items="items"
         class="elevation-1"
         >
        <template v-slot:item.actions="{ item}">
             <v-btn @click="deleteRow(item )">delete</v-btn>
       </template>
        </v-data-table>

function :

 deleteRow(item:any){
      let index=this.items.findIndex(it=>it.email===item.email)
        this.items.splice(index,1);
    }

column headers :

  header = [
        {text:'name',value:'name'},
        {text:'email',value:'email'},
       ,
      {
        text: 'Actions',
        value: 'actions',
        sortable: false
      },
    ]

all other fields will be automatically rendered

var app = new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data: {
    employees: [{
        "id": "1",
        "employee_name": "Tiger Nixon",
        "employee_salary": "320800",
        "employee_age": "61",
        "profile_image": ""
      },
      {
        "id": "2",
        "employee_name": "Garrett Winters",
        "employee_salary": "170750",
        "employee_age": "63",
        "profile_image": ""
      },
      {
        "id": "3",
        "employee_name": "Ashton Cox",
        "employee_salary": "86000",
        "employee_age": "66",
        "profile_image": ""
      },
      {
        "id": "4",
        "employee_name": "Cedric Kelly",
        "employee_salary": "433060",
        "employee_age": "22",
        "profile_image": ""
      },
      {
        "id": "5",
        "employee_name": "Airi Satou",
        "employee_salary": "162700",
        "employee_age": "33",
        "profile_image": ""
      },
      {
        "id": "6",
        "employee_name": "Brielle Williamson",
        "employee_salary": "372000",
        "employee_age": "61",
        "profile_image": ""
      }
    ],
    headers: [{
        text: 'ID',
        value: 'id'
      },

      {
        text: 'employee name',
        value: 'employee_name'
      },
      {
        text: 'employee salary',
        value: 'employee_salary'
      },
      {
        text: 'employee age',
        value: 'employee_age'
      },
      {
        text: 'Actions',
        value: 'actions',
        sortable: false
      },
    ]
  },
  methods: {
    deleteRow(item) {
      let index = this.employees.findIndex(emp => emp.id === item.id)
      this.employees.splice(index, 1);
    }
  }

})
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="096f66677d493c2771">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83f5f6e6f7eae5fac3b1adfb">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet">

<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5325263613617d2b">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="05737060716c637c45372b7d">[email protected]</a>/dist/vuetify.js"></script>

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="app">
  <v-app id="inspire">
    <v-data-table :headers="headers" :items="employees" class="elevation-1">
      <template v-slot:item.actions="{ item }">
             <v-btn @click="deleteRow(item)">delete</v-btn>
       </template>
    </v-data-table>
  </v-app>
</div>

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

Error in Typescript stating that the property 'children' is not found on the imported interface of type 'IntrinsicAttributes & Props'

When I try to import an interface into my Card component and extend CardProps, a yarn build (Typescript 4.5.4) displays the following error: Type error: Type '{ children: Element[]; className: string; border: true; disabled: boolean; }' is not as ...

Definitions for images in the following format

I am currently utilizing typescript in conjunction with NextJs and next-images. Here is the code snippet: import css from "./style.sass"; import img from './logo.svg'; import Link from 'next/link'; export default () => <Link hre ...

Creating an array of objects using Constructors in Typescript

Utilizing TypeScript for coding in Angular2, I am dealing with this object: export class Vehicle{ name: String; door: { position: String; id: Number; }; } To initialize the object, I have followed these steps: constructor() { ...

Vue element fails to appear on the screen

As a newcomer to Vue.js and web development in general, I decided to dive into the vuejs guide. Something puzzled me - when creating a vue component using Vue.component(NameOfComponent, {...}) and inserting it into my HTML as <NameOfComponent></ ...

What is the best way to pass an array through router navigate function?

I've searched for a solution in other questions, but nothing has helped me... My goal is to redirect to a URL like this: this.router.navigateByUrl('/products'); I want to pass an array and retrieve it in the component with the active link ...

Best practices for handling APIs in Vue

After spending hours reading documentation and searching online for the best way to manage API calls in larger projects, I have yet to find a solution that meets my needs. My goal is to create a service or facade for the backend that can be easily integra ...

Obtain the hexadecimal color code based on the MUI palette color name

Is there a way to extract a hexcode or any color code from a palette color name in Material UI? Here is my use case: I have a customized Badge that I want to be able to modify just like the normal badges using the color property. The component code looks ...

What is the proper way to utilize the ES6 import feature when using a symbolic path to reference the source file?

I am seeking a deeper understanding of the ES6 import function and could use some assistance. The Situation Imagine that I have a portion of code in my application that is frequently used, so I organize all of it into a folder for convenience. Now, in t ...

What steps should I follow to set up a TypeScript project that incorporates JavaScript modules compiled from PureScript?

TL;DR I am looking to develop TypeScript typings for compiled PureScript modules and include them in my npm package. I am willing to manually maintain these typings, but I am struggling with the configuration needed in tsconfig.json (up and downstream) and ...

When a card is clicked in the parent component, data is sent to the child component in Angular. The card contains an image, name, ID,

How can I pass data from a parent component (nfts) to a child component (main) when a card is clicked? The card contains images, ids, names, and more information. I've attempted using @Input() but haven't been able to receive the value in the ch ...

Firebase hosting adjusts the transparency of an element to 1% whenever it detects the presence of CSS opacity

I'm currently working on a website using Vue.js and Firebase. Everything runs smoothly locally, including a button with a desired low opacity. However, when I deploy the site to Firebase Hosting, the button's opacity inexplicably changes to 1% an ...

Is it possible to transfer the setState function between different contextProviders?

I'm encountering difficulties in setting a state when passing the context provider to other elements. Here is my code snippet. I have created a FancyboxContext so that I can easily access it from anywhere in the app. import React, { createContext, use ...

Limit children in Preact/Typescript to only a designated component

Is it feasible to restrict the type of component allowed as children in React? For example: function ListItem() { return ( <div> {this.props.children} </div> ); } function OrderedList(children: <Lis ...

What is the syntax for implementing this function in TypeScript?

When developing applications in react and typescript, I find myself frequently creating helper functions. However, there are two key points that always give me pause. One of my functions is provided below, showcasing the common dilemmas I face. What shoul ...

AWS Amplify is failing to maintain the user session post a successful login

Currently, I am developing an aws-serverless application using React. My main issue lies in the authentication process with aws-amplify. The authentication works smoothly, but the session is not being preserved. During the signing-in stage: await Auth.s ...

Some elements that fit the criteria of 'number | function' are not callable at all

Consider a basic function like this: export const sum = (num?: number) => { const adder = (n: number) => { if (!n) { return num; } num = (num && num + n) || n; return adder; }; return a ...

A guide on implementing multiple ternary operators in a Vue.js template

Is it possible for a template to return three different values instead of just two, based on the data? I am familiar with using two conditions, but is there a way to use more than two without getting a syntax error? <option {{ change === 1 ? &apos ...

Angular 5 does not recognize the function submitEl.triggerEventHandler, resulting in an error

Greetings! I am currently working on writing unit test cases in Angular5 Jasmine related to submitting a form. Below is the structure of my form: <form *ngIf="formResetToggle" class="form-horizontal" name="scopesEditorForm" #f="ngForm" novalidate (ngSu ...

Can someone guide me on creating a slideshow using Ionic?

Having trouble integrating a javascript/css slideshow into Ionic. Ionic does not support the use of ".style" in elements. Need assistance, below is the code: <head> <title>Slideshow</title> <style> .slides {display:none;} </styl ...

An empty constant object can trigger an endless cycle of re-rendering

Consider this simplified scenario: export function myCustomHook<TData = Record<string,string>> (data?: TData) { const [output, setOutput] = useState<number>(); const customFunction(data?: TData) { //In a real scenario : p ...