问题描述
我正在一个Electron项目中使用Vue CLI项目和Vue CLI Plugin Electron Builder。除了我最近发现的一个怪异的错误之外,一切都很好。
每当我在页面之间导航时(Vue路由器),我从组件mounted()
属性中侦听的事件都会变成两倍。实际上是N+1
问题。
为了更清楚地描述问题,我有两个Home.vue
和HelloWorld.vue
组件。从Home.vue
组件,每当单击按钮并从同一组件main
属性监听event.reply()
时,我都会向mounted()
进程发送事件。现阶段完全符合预期。
但是,每当我进入HelloWorld
页面并再次切换回Home
页面时,以及当我单击按钮以从{{1}发送和接收event
时, }的过程中,即使我只单击一次,我也不会只看到一个main
,而是看到两个event
的答复。如果我再次在页面之间切换,我会看到三个event
的回复,诸如此类event
的问题。
为方便起见,我快速制作了一个GIF,可以清楚地显示问题。
N+1
Home.vue
<template>
<div class="home">
<button @click="send()">Home</button>
</div>
</template>
<script>
export default {
name: "Home",data() {
return {
cause: null
}
},mounted() {
window.ipcRenderer.on("home:reply",event => console.log(event));
},methods: {
send() {
window.ipcRenderer.send("home");
}
},};
</script>
main.js
我在Vue路由器上没有什么特别的,这只是Vue CLI随附的默认支架。如您在上面的代码片段中所看到的,我所做的只是在单击按钮时发送一个事件,并侦听来自相同组件ipcMain.on("home",event => {
return event.reply("home:reply");
});
属性的相同事件回复。
我还在堆栈溢出上发现了a similar topic,但自己却不知道。我不知道我的代码有什么问题?
解决方法
当组件被破坏时,您需要注销事件处理程序,否则,每次安装组件时,您将一次又一次地注册相同的事件处理程序。
mounted() {
window.ipcRenderer.on('home:reply',this.handleHomeReply)
},destroyed() {
window.ipcRenderer.off('home:reply',methods: {
handleHomeReply(event) {
console.log(event)
}
}