[Vuejs]-Understanding and Implementing Advanced Event Handling in Vue.js: Dealing with Event Modifiers and Event Filtering

0👍

You can do something like this:

<template>
  <div>
    <item-component v-for="item in items" :key="item.id" :data-id="item.id" v-on="item.events" />
  </div>
</template>

<script>
export default 
{
  data() 
  {
    return {
      items: [
        { 
          id: 1, 
          name: "item 1", 
          events:
          {
            click: this.handleClick,
            mouseenter: this.handleMouseEnter,
            mousemove: this.handleMouseMove,
          }
        },
        { 
          id: 2, 
          name: "item 2", 
          events:
          {
            click: this.handleClick,
          }
        },
        { 
          id: 3, 
          name: "item 3", 
          events:
          {
            mousemove: this.handleMouseMove,
          }
        },
      ]
    };
  },
  methods: 
  {
    handleClick(event) 
    {
      console.log("CLICK", event.target.dataset.id);
    },
    handleMouseEnter(event) 
    {
      console.log("MOUSE ENTER", event.target.dataset.id);
    },
    handleMouseMove(event) 
    {
      console.log("MOUSE MOVE", event.target.dataset.id);
    },
  }
};
</script>

You should make sure that your item-component is emitting the events that you’re listening for.

Leave a comment