Tanmay
Tanmay

Reputation: 3159

How to receive the second argument from this.$emit() in vuejs?

I have a custom input element my-input in MyInput.vue:

<input :value="value" @input="inputOccurred($event.target.value)">

In my inputOccurred method, I am emitting oninputoccurred custom event and also passing the value:

inputOccurred: function(value){
     this.$emit('oninputoccurred', value);
}

But how can I receive the passed value from the parent component? And where does the second argument (value) go from this.$emit()?

 <my-input @oninputoccurred="printValue(<!-- How do I get the value here -->)"></my-input>

Upvotes: 1

Views: 944

Answers (1)

Lawrence Cherone
Lawrence Cherone

Reputation: 46610

Here is a basic example of sending a value to a component :in then internally setting the components model this.value, then upon @input send the current value back to the parent via emitting it.

Vue.component('myInput', {
  template: '#input-template',
  props: ['in'],
  data () {
    return {
      value: this.in
    }
  },
  methods: {
    inputOccurred (e) {
      // set the model
      this.value = e.target.value
      this.$emit('on-out', this.value.split("").reverse().join(""))
    }
  }
});

//
var vm = new Vue({
  el: '#app',
  data () {
    return {
      value: 'Sent from parent, reverse by typing a value'
    }
  },
  methods: {
    setValue (value) {
      this.value = value
    }
  }
});
<script src="https://cdn.jsdelivr.net/vue/1.0.16/vue.js"></script>
<div id="app">
  <my-input :in="value" @on-out="setValue"></my-input>
  
  {{ value }}
</div>

<template id="input-template">
  <input :value="value" @input="inputOccurred">
</template>

Upvotes: 2

Related Questions