简体   繁体   中英

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. 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)
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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