I want to emit
an custom event to bubble up from the grandchild through the child element to the parent element. But it doesn't work. Even to trigger the event directly on the parent nor the child element does not work.
<div id="example-app" >
<parent>
<child>
<grandchild></grandchild>
</child>
</parent>
</div>
Here the Component Code:
Vue.component('parent', {
template: ` <div @testevent="test" style="padding: 10px; background-color: red; border: 1px solid black;">
<button @click="$emit('testevent')">Parent Button</button>
<button @click="test">Triggger Test Manueally</button>
<slot ></slot>
</div>`,
methods: {
test () {
alert('Test ok')
}
}
})
Vue.component('child', {
template: ` <div style="padding: 10px; margin: 5px; background-color: green; border: 1px solid black;">
<button @click="$emit('testevent')">Child Button</button><br>
<slot></slot>
</div>`
})
Vue.component('grandchild', {
template: `<div style="padding:10px; margin: 5px; background-color: white; border: 1px solid black;">
<button @click="$emit('testevent')">Grandchild Button</button>
</div>`
})
new Vue({
el: '#example-app',
})
You could try something like this:
Vue.component('parent', {
template: ` <div style="padding: 10px; background-color: red; border: 1px solid black;">
<button @click="$emit('testevent')">Parent Button</button>
<button @click="test">Triggger Test Manueally</button>
<slot ></slot>
</div>`,
methods: {
test () {
alert('Test ok')
}
},
mounted: function() {
this.$on('testevent', () => {
this.test()
})
}
})
Vue.component('child', {
template: ` <div style="padding: 10px; margin: 5px; background-color: green; border: 1px solid black;">
<button @click="$emit('testevent')">Child Button</button><br>
<slot></slot>
</div>`,
mounted: function() {
this.$on('testevent', () => {
this.$parent.$emit('testevent')
})
}
})
Vue.component('grandchild', {
template: `<div style="padding:10px; margin: 5px; background-color: white; border: 1px solid black;">
<button @click="$parent.$emit('testevent')">Grandchild Button</button>
</div>`
})
new Vue({
el: '#example-app',
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="example-app" >
<parent>
<child>
<grandchild></grandchild>
</child>
</parent>
</div>