I am sending an event from a child ponent 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 ponents and Vue-router.
As an aside, I have found very few VueJS examples use single file ponents, and for a noob, transpiling from the simple Vue app in one file to multiple single file ponents can be confusing.
Parent:
<template>
....html here
</template>
<script>
import Child from './Child.vue'
export default {
name: 'Parent',
data () {
return {
stage: 1
}
},
ponents: {
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?
I am sending an event from a child ponent 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 ponents and Vue-router.
As an aside, I have found very few VueJS examples use single file ponents, and for a noob, transpiling from the simple Vue app in one file to multiple single file ponents can be confusing.
Parent:
<template>
....html here
</template>
<script>
import Child from './Child.vue'
export default {
name: 'Parent',
data () {
return {
stage: 1
}
},
ponents: {
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?
Share Improve this question asked Mar 29, 2017 at 11:40 Don SmytheDon Smythe 9,84415 gold badges65 silver badges108 bronze badges 1- 1 An example of multiple files and a build step - github./jonataswalker/vue-rollup-example – Jonatas Walker Commented Mar 29, 2017 at 12:01
1 Answer
Reset to default 7Another way of setting the on
event would be referencing the listener method directly from the place where you call the child ponent.
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;
}
}