Search code examples
vuetify.jsv-data-table

Vuetify - How to access element in v-data-table at current cursor position


I'm using v-data-table to list locations that are also shown on a map. It would be nice to synchronize the highlighting so that if the cursor hovers over a location in the table, the same location would be highlighted on the map.

Is there a way to access the element in v-data-table where the cursor is currently hovering over?


Solution

  • As one of the possible solutions you can override #items slot and include native mouseover event into <tr> tag:

    <span class="text-h6">{{ `Last hovered location: ${hoveredLocation}` }}</span>
    <v-data-table
      :headers="headers"
      :items="locations"
      :items-per-page="5"
    >
      <template #item="{ item }">
        <tr @mouseover="onMouseOver(item)">
          <td>{{ item.city }}</td>
          <td>{{ item.country }}</td>
        </tr>
      </template>
    </v-data-table>
    ...
    data () {
      return {
        hoveredLocation: null,
        headers: [
          { text: 'City', value: 'city' },
          { text: 'Country', value: 'country' },
        ],
        locations: [
          { id: 3, city: 'Paris', country: 'France'},
          ...
        ],
      }
    },
    methods: {
      onMouseOver(item) {
        this.hoveredLocation = `${item.city} (${item.country})`;
      }
    }
    

    Possibly you need to combine several events like mouseover/out, mouseenter/leave, etc.

    Test this at CodePen.