Search code examples
vue.jseventsvuejs2

Pass event modifiers with v-on object syntax


According to vue we can pass events and handlers as objects (very useful for slots).

Script

computed: {
  on() {
    return {
      input: this.onInput,
      keyup: this.onEnter
    }
  }
}

Template

<template>
  <div>
    <slot name="mySlot" :on="on"></slot>
  </div>
<template>

So in this example, lets say the slot takes an input field. In this case, that input field will emit every input event and key up event. Both these events will be caught by the 'child component' which is the one defined here, that declares the slot.

However if we just wanted to get the 'enter' keyup event, this syntax doesn't seem to work.

Script

computed: {
  on() {
    return {
      input: this.onInput,
      'keyup.enter': this.onEnter
    }
  }
}

Using the above, the keyup enter event is not caught. Anyone know how to reconcile the syntax here, so the events can be caught?


Solution

  • Even though the accepted answer solved the OP problem, it is not exactly answering the question and thus is not applicable for other cases.

    Now, with Vue3, script setup syntax and render function API withModifiers we can actually do what OP originally asked for:

    <script setup>
    import { withModifiers } from 'vue';
    
    const doSth = (e) => {
      // ...
    }
    
    const on = {
      input: doSth,
      keyup: withModifiers(doSth, ['enter', 'stop']), // any other modifier you need
    }
    </script>
    
    <template>
      <div>
        <slot name="mySlot" :on="on"></slot>
      </div>
    </template>
    

    The withModifiers function is designed to be used in render function, but I've confirmed that it works this way too.