[英]listening to javascript custom event inside vuejs component
I created a custom event and dispatched it in my main page script, which includes a Vue component.我创建了一个自定义事件并在我的主页脚本中分派它,其中包括一个 Vue 组件。 How do I listen to that event from inside the Vue component?我如何从 Vue 组件内部收听该事件?
main.blade.php: 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:由于您在document.body
调度,因此您的组件可以使用mounted()
钩子中的addEventListener
和beforeDestroy()
钩子中的removeEventListener
来监听document.body
上的事件:
// 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)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.