In a VUE project development, postMessage was used and message events were monitored on each page, but multiple requests were sent repeatedly. The first thought was to bind the addEventListener event to the window and not remove the event. I then called removeEventListener when I left the component to remove the event, but it didn’t work.

The wrong sample

The following operation cannot remove the message event

Mounted () {window.adDeventListener ('message', (e)=> {if (this.mkdmfull? e.data === this.mkdmFull : e.data === this.mkdm) { this.getData(); this.mixinClearSelected(); } }, false); }, beforeDestroy() { window.removeEventListener('message', (e)=> { if (this.mkdmFull ? e.data === this.mkdmFull : e.data === this.mkdm) { this.getData(); this.mixinClearSelected(); }, false); }Copy the code

The second parameter handler for the event listener found in Vue needs to be bound to this, and the corresponding parameters in removeEventListener and addEventListener need to be the same

The correct sample

Mounted () {/ / for details close to refresh the list window. The addEventListener (' message ', enclosing listenerPostMessage, false); }, methods: { listenerPostMessage() { if (this.mkdmFull ? e.data === this.mkdmFull : e.data === this.mkdm) { this.getData(); this.mixinClearSelected(); } } }, beforeDestroy() { window.removeEventListener('message', this.listenerPostMessage, false); }Copy the code

This pit is still a little pit, after stepping on a know!