Ahmed Rafie
Ahmed Rafie

Reputation: 101

use @contextmenu event with vuetify v-data-table

I am trying to build a custom contextmenu that pops up when right-clicking a row in the v-data-table component .

how can I achieve that ?

Upvotes: 3

Views: 5031

Answers (1)

Narxx
Narxx

Reputation: 8299

There are 2 ways to accomplish that.

Using regular v-data-table rows

Simply add the contextmenu:row event listen to the v-data-table component, and enjoy the magic of each row emitting this event on right-click. Capture this event and handle it on JS.

<v-data-table :items="myItems"
              :headers="headers"
              @contextmenu:row="rightClickHandler"
              ...
/>

Then you do whatever you want with the event and the item emitting that event

methods: {
  rightClickHandler(event, item) {
    // do something with event and/or item
    console.log(event, item)
  }
}

NOTE: will not emit when table rows are defined through a slot such as item or body.

Using table with item / body slots

When using slots to cutom build your own table rows, you will need to manually trigger the event on each row yourself

<v-data-table
  :headers="headers"
  :items="myItems"
  ...
  <template v-slot:body="{ items }">
    <tbody>
      <tr v-for="(item, index) in items"
          :key="item.id"
          @contextmenu="rightClick($event, item)"
          ...

And on the script side, simply implement the function to handle the event, and the item being clicked on

methods: {
  rightClick(event, item) {
    console.log(item)
    event.preventDefault()
  },

Upvotes: 7

Related Questions