在 Vue 路由器页面之间切换会导致 VueJS mounted() 上发生多个事件
Switching between Vue Router pages cause multiple event fire on VueJS mounted()
我正在研究 Electron project where I use Vue CLI project and the Vue CLI Plugin Electron Builder。一切都很好,除了我最近发现的一个奇怪的错误。
每当我在页面 (Vue Router) 之间导航时,我从组件 mounted()
属性 监听的事件变为双倍。这实际上是 N+1
问题。
为了更清楚地描述问题,我有两个 Home.vue
和 HelloWorld.vue
组件。从 Home.vue
组件,每当单击按钮并从同一组件 mounted()
属性 监听 event.reply()
时,我都会向 main
进程发送一个事件。现阶段完全符合预期。
但是,每当我转到 HelloWorld
页面并再次切换回 Home
页面,以及当我单击按钮从 [=] 发送和接收 event
17=] 过程中,我不仅看到了一个 event
,即使我只点击了一次,但我看到了两个 event
回复。如果我再次在页面之间切换,我会看到三个 event
回复等等 N+1
问题。
为方便起见,我制作了一张快速 GIF 动图,可以清楚地显示问题。
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
ipcMain.on("home", event => {
return event.reply("home:reply");
});
我在 Vue 路由器上没有任何特殊之处,它只是 Vue CLI 附带的默认脚手架。正如您在上面的代码片段中看到的,我所做的只是在单击按钮时发送一个事件并监听来自同一组件的同一事件回复 mounted()
属性.
我还在 Stack Overflow 上找到了 a similar topic,但我自己搞不懂。我不知道我的代码有什么问题
您需要在销毁组件时注销事件处理程序,否则每次挂载组件时,您将不断注册相同的事件处理程序。
mounted() {
window.ipcRenderer.on('home:reply', this.handleHomeReply)
},
destroyed() {
window.ipcRenderer.off('home:reply', this.handleHomeReply)
},
methods: {
handleHomeReply(event) {
console.log(event)
}
}
我正在研究 Electron project where I use Vue CLI project and the Vue CLI Plugin Electron Builder。一切都很好,除了我最近发现的一个奇怪的错误。
每当我在页面 (Vue Router) 之间导航时,我从组件 mounted()
属性 监听的事件变为双倍。这实际上是 N+1
问题。
为了更清楚地描述问题,我有两个 Home.vue
和 HelloWorld.vue
组件。从 Home.vue
组件,每当单击按钮并从同一组件 mounted()
属性 监听 event.reply()
时,我都会向 main
进程发送一个事件。现阶段完全符合预期。
但是,每当我转到 HelloWorld
页面并再次切换回 Home
页面,以及当我单击按钮从 [=] 发送和接收 event
17=] 过程中,我不仅看到了一个 event
,即使我只点击了一次,但我看到了两个 event
回复。如果我再次在页面之间切换,我会看到三个 event
回复等等 N+1
问题。
为方便起见,我制作了一张快速 GIF 动图,可以清楚地显示问题。
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
ipcMain.on("home", event => {
return event.reply("home:reply");
});
我在 Vue 路由器上没有任何特殊之处,它只是 Vue CLI 附带的默认脚手架。正如您在上面的代码片段中看到的,我所做的只是在单击按钮时发送一个事件并监听来自同一组件的同一事件回复 mounted()
属性.
我还在 Stack Overflow 上找到了 a similar topic,但我自己搞不懂。我不知道我的代码有什么问题
您需要在销毁组件时注销事件处理程序,否则每次挂载组件时,您将不断注册相同的事件处理程序。
mounted() {
window.ipcRenderer.on('home:reply', this.handleHomeReply)
},
destroyed() {
window.ipcRenderer.off('home:reply', this.handleHomeReply)
},
methods: {
handleHomeReply(event) {
console.log(event)
}
}