I created a custom event and dispatched it in my main page script, which includes a Vue component. How do I listen to that event from inside the Vue component?
main.blade.php:
<body>
<insert-block></insert-block>
<script>
const insert_block_event = new CustomEvent('insert_block', { detail: 'some detail goes here' });
document.body.dispatchEvent(insert_block_event);
</script>
</body>
Since you're dispatching on document.body
, your component could listen to the event on document.body
with addEventListener
in the mounted()
hook, and removeEventListener
in the beforeDestroy()
hook:
// MyComponent.vue
export default {
mounted() {
document.body.addEventListener('insert_block', this.onInsertBlock)
},
beforeDestroy() {
document.body.removeEventListener('insert_block', this.onInsertBlock)
},
methods: {
onInsertBlock(e) {
console.log('insert_block', e)
}
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments