I am sending an event from a child component to it's parent. I want to intercept the signal via a method in the parent. But the listening function fires always regardless of whether an event has been emitted. Note that I am using single file components and Vue-router.
As an aside, I have found very few VueJS examples use single file components, and for a noob, transpiling from the simple Vue app in one file to multiple single file components can be confusing.
Parent:
<template>
....html here
</template>
<script>
import Child from './Child.vue'
export default {
name: 'Parent',
data () {
return {
stage: 1
}
},
components: {
Child
},
created: function () {
// the following line always runs even when listen for non-existent event eg this.$on('nonsense'...)
this.$on('child-event', this.stage = 2)
}
}
child:
<template>
<button v-on:click="sendEvent" type="button" class="btn btn-success">Next</button>
</template>
<script>
export default {
name: 'Child',
data () {
return {
response_status: 'accepted'
}
},
methods: {
sendEvent: function () {
this.$emit('child-event', 'accepted')
}
}
Any idea what I am doing wrong?
Another way of setting the on
event would be referencing the listener method directly from the place where you call the child component.
On your parent template you could do something like:
<Child v-on:child-event="eventIsEmitted"></Child>
On your methods
:
eventIsEmitted: function(status) {
if (status == 'accepted') {
this.stage = 2;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With