Search code examples
javascriptvue.jsinputvuejs2onkeyup

Use keyup enter on custom input field - Vue JS


I have to use keypu.enter in a custom input component on Vue. I want that the component <input /> can execute a function hosted in parent component after a enter key event during typing
This is the component code

<input v-on:keyup.enter="$emit('keyup')"/>

And there are the main page

<template>
  <se-input @keyup="function()"/>
</template>

<script>
import inputField from '../components/inputfield.vue'

export default {
  name: 'inputField',
  components: {
      'custom-input': inputField
    },
  },
  methods: {
    function () {
      // Function
    }
  }
}
</script>

Solution

  • Try to pass value to your custom event, and in parent component listen to that event :

    Vue.component('seInput', {
      template: `
        <div class="">
          <input v-on:keyup.enter="$emit('keyup', $event.target.value)"/>
        </div>
      `
    })
    
    new Vue({
      el: '#demo',
      data() {
        return {
          inputValue: null
        }
      },
      methods: {
        handleInput(val) {
          this.inputValue = val
        }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="demo">
      <h3>{{ inputValue }}</h3>
      <se-input @keyup="handleInput"/>
    </div>