在Vue路由器页面之间切换会在VueJS Mounted上引发多个事件

问题描述

我正在一个Electron项目中使用Vue CLI项目和Vue CLI Plugin Electron Builder。除了我最近发现的一个怪异的错误之外,一切都很好。

每当我在页面之间导航时(Vue路由器),我从组件mounted()属性中侦听的事件都会变成两倍。实际上是N+1问题。

为了更清楚地描述问题,我有两个Home.vueHelloWorld.vue组件。从Home.vue组件,每当单击按钮并从同一组件main属性监听event.reply()时,我都会向mounted()进程发送事件。现阶段完全符合预期。

但是,每当我进入HelloWorld页面并再次切换回Home页面时,以及当我单击按钮以从{{1}发送和接收event时, }的过程中,即使我只单击一次,我也不会只看到一个main,而是看到两个event的答复。如果我再次在页面之间切换,我会看到三个event的回复,诸如此类event的问题。

为方便起见,我快速制作了一个GIF,可以清楚地显示问题。

sending and receiving event from the Electron main process

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...