Modermo
Modermo

Reputation: 1992

Passing argument into $emit returning undefined

I have a simple app that captures whatever is in an input, and prints it in a h1.

<div id="app">  
  <div>
    <module v-on:button-pressed="parentPrint(capturedInput)"></module>
  </div>
  <h1>{{ h1Text }}</h1>
</div>

The problem is, the h1 will not update to reflect the input value.

Vue.component('module', {
  template:`
    <div>
      <input type="text" placeholder="Type Something Awesome" v-model="capturedInput" />
      <button v-on:click="activateButtonPress">Change text</button>
    </div>
  `,
  data(){
    return {
      capturedInput: ''
    }
  },
  methods:{
    activateButtonPress: function(){
      console.log(this.capturedInput)
      this.$emit('button-pressed', this.capturedInput)
    }
  }
})

new Vue({
  el:'#app',
  data:{
    h1Text: 'Should reflect user input'
  },
  methods:{
    parentPrint: function(capturedInput){
      this.h1Text = capturedInput;

    }
  } 
})

How do I actually pass data into the emit and have it available in the parent scope? capturedInput keeps returning undefined for me.

Upvotes: 2

Views: 6067

Answers (1)

Lance Whatley
Lance Whatley

Reputation: 2455

When you define your event handler in your parent, you don't need to add an argument like you are. Any/All params you pass when you emit from the child will get sent to the parent.

So change

<module v-on:button-pressed="parentPrint(capturedInput)"></module>

to

<module v-on:button-pressed="parentPrint"></module>

If you only pass 1 argument from your child like you are now in this.$emit('button-pressed', this.capturedInput), just add a single parameter in the parent method you're calling. If you passed 2 paramters from the child such as this.$emit('button-pressed', this.capturedInput, '2nd'), you could just add another parameter in the parent method definition to capture it.

EDIT: codepen of this working: https://codepen.io/anon/pen/rGmXbx

Upvotes: 8

Related Questions