vue.jsvuejs3

Getting the value of the special key attribute of the element that sent the event in Vue


I know key is a special attribute but is there a way to access its value and avoid redundantly assigning the value to a data attribute like the following?

<script setup>
function onButtonClick(event) {
  alert('Key: ' + event.target.dataset.key)
}
</script>

<template>
  <button @click="onButtonClick" v-for="key in [1, 2, 3, 4]" :key="key" :data-key="key">
    Get {{ key }}
  </button>
</template>

<style>
  button {
    display: block; 
    margin-bottom: 5px;
  }
</style> 

See playground.


Solution

  • This difficulty means that the signature of onButtonClick is lacking. There is no need for data-key, instead the handler needs to receive all data it needs through arguments:

    @click="onButtonClick($event, key)"
    

    In case onButtonClick doesn't use mouse event object:

    @click="onButtonClick(key)"
    

    In case this functionality is meant to be reusable, this is the case for a directive:

    {
      beforeMount(el, binding, vnode) {
        el._keyOnClickHandler = () => {
          console.log(`Key: ${vnode.key}`);
        };
    
        el.addEventListener('click', el._keyOnClickHandler);
      },
      unmounted(el) {
        el.removeEventListener('click', el._keyOnClickHandler);
      }
    }