繁体   English   中英

在 vuejs 组件中监听 javascript 自定义事件

[英]listening to javascript custom event inside vuejs component

我创建了一个自定义事件并在我的主页脚本中分派它,其中包括一个 Vue 组件。 我如何从 Vue 组件内部收听该事件?

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>

由于您在document.body调度,因此您的组件可以使用mounted()钩子中的addEventListenerbeforeDestroy()钩子中的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM