Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does @input="$emit('input', $event)" means in vue component?

I am reading some code that I want to update:

<b-input :value="value" @input="$emit('input', $event)" ref="input" :maxlength="maxlength"/>

what does @input="$emit('input', $event)" stand for? Where and how can I listen for the input event?

like image 848
Petran Avatar asked Nov 08 '18 13:11

Petran


People also ask

What are the 3 parts of a component in Vue?

Components in Vue are composed of three parts; a template (which is like HTML), styles and JavaScript. These can be split into multiple files or the same .

What does this refer to in Vue component?

The this keyword within Vue gives you easy access to all of your data and functionalities. Wether you want to access a data property, a computed property, a component prop or a function, you can all find them directly on the this keyword.

What does $emit do in Vue?

Vue $emit is a function that lets us emit, or send, custom events from a child component to its parent. In a standard Vue flow, it is the best way to trigger certain events.


2 Answers

@input is the short-hand for v-on:input which binds to the component's input event. vm.$emit is documented here and has an example with a similar use-case here.

In your case your component simply emits an event with the same name and the same arguments as the one it receives from its child b-input. Programatically you can listen to these events with vm.$on, e.g. in your mounted method:

export default {
  components: { BInput },

  mounted () {
    this.$on('input', (event) => {
      console.log(event);
    });
  }
}
like image 62
padarom Avatar answered Sep 22 '22 21:09

padarom


$emit is data passed to an other component, see this example:

Component: getEmit.vue

<template>
  <!--get data-->
  <button-emit v-on:data="getValue"></button-emit>
</template>
<script>
  import buttonEmit from './buttonEmit'
  export default {
    name: 'getEmit',
    components: { buttonEmit },
    methods: {
      // get payload in parameter
      getValue(event) {
        alert('Get Emit Success' + event)
      }
    }
  }
</script>

Component: buttonEmit.vue

<template>
  <button @click="emit($event)"></button>
</template>
<script>
  export default {
    name: 'buttonEmit',
    methods: {
      emit(event) {
      // Emit text data the payload event
        this.$emit('data', event)
      }
    }
  }
</script>
like image 29
Hamilton Gabriel Avatar answered Sep 20 '22 21:09

Hamilton Gabriel