4

I am using Vue.js 2.0 and I am trying to emit an event from child component to parent component but it's not working.

You can see my code below:

child component:

<template>
  <button @click="confirmSendMessage">Send</button>
</template>

<script>
  export default {
    methods: {
      confirmSendMessage () {
        this.$emit('confirmed')
      }
    }
</script>

parent component:

<template>
    <ConfirmMessage/>
</template>

<script>
    import ConfirmMessage from './ConfirmMessage'
    export default {
        events: {
           confirmed() {
              console.log('confirmed')
           }
        },
        components: {
            ConfirmMessage
        }
   }
</script>

When I click on the button, nothing appears to me on the Chrome console. I don't know why. Can anybody help me? I am new on Vue JS.

Pierce O'Neill
  • 385
  • 9
  • 22
Leonardo Santos
  • 300
  • 7
  • 16

2 Answers2

7

You missed to listen the emitted event. Use v-on to listen to the event:

<!--                               vv -> call method -->
<ConfirmMessage v-on:confirmed="confirmed" />
<!--                  ^^ -> emitted event -->
tony19
  • 125,647
  • 18
  • 229
  • 307
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
  • Now I got this on console: `Property or method "confirmed" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.` :S – Leonardo Santos Mar 20 '18 at 15:18
3

You have to listen the events, if you look the Emit Documentation, it expects as first argument the name of the event as string, an then the values (if you have) you want to pass to the listener.

so it will be:

<confirm-message :nameOfEvent="functionToExecuteWhenTheEventIsEmitted" />

the method will be:

functionToExecuteWhenTeEventIsEmitted(someValue) { //do whatever with someValue}

and on the child:

this.$emit('nameOfEvent', someValue)

In your case

You aren't passing values so this.$emit('confirmed') and <ConfirmMessage :confirmed="confirmed"> it will be enought

tony19
  • 125,647
  • 18
  • 229
  • 307
DobleL
  • 3,808
  • 14
  • 20