Navigating between Vue Router pages triggers multiple events within the mounted() lifecycle of VueJS

Currently, I am immersed in a project using Electron with a Vue CLI setup and the Vue CLI Plugin Electron Builder. The overall functionality is working perfectly fine except for a peculiar bug that has recently surfaced.

The issue arises when navigating between pages using the Vue Router - the event listener in the component's `mounted()` property gets triggered twice, resulting in an 'N+1' problem.

To elaborate on this predicament, within my project, I have two components named `Home.vue` and `HelloWorld.vue`. In `Home.vue`, upon clicking a button, I trigger an event to the main process and listen for the corresponding event reply using the `mounted()` property of the same component. Initially, everything functions as expected.

However, upon switching to the `HelloWorld` page and then returning to the `Home` page, every click of the button not only sends one event but receives two event replies from the main process. This behavior exacerbates when switching back and forth between pages, revealing a pattern resembling the 'N+1' issue.

In order to illustrate the problem more clearly, I have created a GIF showcasing the issue: https://i.sstatic.net/pDnBt.gif

Home.vue

<template>
  <div class="home">
    <button @click="send()">Home</button>
  </div>
</template>

// Script section

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

My Vue Router configuration is based on the default structure provided by Vue CLI. As evident from the code snippet above, I simply trigger an event upon button click and await the respective event reply using the `mounted()` property within the same component.

I did come across a similar discussion on Stack Overflow here, but unfortunately, I haven't been able to resolve the issue myself. At this point, I'm baffled as to what might be causing this discrepancy in my code 🥱

Answer â„–1

It's important to remember to unregister the event handler when the component is destroyed. If you forget, you'll end up re-registering the same event handler every time the component is mounted, leading to potential issues.

mounted() {
  window.ipcRenderer.on('app:reply', this.handleAppReply)
},

destroyed() {
  window.ipcRenderer.off('app:reply', this.handleAppReply)
},

methods: {
  handleAppReply(event) {
    console.log(event)
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to implement the UI router into my Angular Framework

I've been working on a framework that is supposed to be router agnostic. While I've managed to make it work with ngRoute, I just can't seem to get it functioning with UI Router. Here's a snippet of the main app module: (function () { ...

What is the best way to collect and store data from various sources in an HTML interface to a Google Spreadsheet?

Currently, I have a spreadsheet with a button that is supposed to link to a function in my Google Apps Script called openInputDialog. The goal is for this button to open an HTML UI where users can input text into five fields. This input should then be adde ...

Tips for confirming a sub string is present in an array using JavaScript/TScript

I am currently testing for the presence of a SubString within an array. In my test, I am asserting using: expect(classList).toContain('Rail__focused') However, I encountered the following error: Error: expect(received).toContain(expected // inde ...

Ways to enhance radio imagery selection?

I'm just starting out with JS and could really use some guidance on how to improve my code. I think it might need a single function for all options, but I'm not sure. It's working fine right now, but I have a feeling it could be better ;) H ...

What is the best way to obtain the value of a Promise within a function?

When working with Promises, accessing the value inside the .then method is simple. Take a look at this example: const Promise = require("bluebird"); const fs = Promise.promisifyAll(require('fs')); const mergeValues = require('./helper' ...

The IntroJs step is only partially visible on the screen

Currently, I am incorporating introJS into my application and encountering an issue where one of the steps is only partially visible on the screen. Despite trying various position settings such as auto, left, right, etc., this particular item consistentl ...

Filter out specific fields from an object when populating in MongoDB using the aggregate method

Is there a way to use the populate() function in MongoDB to exclude specific fields like email and address, and only retrieve the name? For example: const results = await Seller.aggregate(aggregatePipeline).exec(); const sellers = await Seller.populate(re ...

The plugin function cannot be executed unless inside the document.ready event

Utilizing jquery and JSF to construct the pages of my application includes binding functions after every ajax request, such as masks and form messages. However, I am encountering an issue where I cannot access the plugins outside of $(function(). (functio ...

Generate list items based on a PHP array using JavaScript

Upon fetching data from my database, I receive a PHP array structured as follows: $dbResult = array([0] => array([a] => 1 [b] => 1 [c] => 1) [1] => array([a] => 2 [b] => 2 [c] => 2) [3] => arr ...

Developing a universal.css and universal.js file for a custom WordPress theme

I have developed a custom WordPress theme with an extensive amount of code. To manage the numerous style and script files, I have segmented them into multiple individual files. To integrate all these files into my template, I utilized the following code w ...

Transforming data with D3.js into a string representation

Recently, I stumbled upon a function called "stringify" that seems like a fantastic tool for converting flat data into a Json format. If this function lives up to its potential, it could potentially save me countless hours of writing recursive code in ASP ...

Implementing theme in Monaco editor without initializing an instance

I recently developed a web application incorporating Monaco Editor. To enhance user experience, I also integrated Monaco for syntax highlighting in static code blocks. Following guidance from this source, I successfully implemented syntax highlighting wit ...

Tips for obtaining the state of a local variable in a Vue method:

How do I access the state of a local variable within a method in Vue? I am looking to set a specific value for the dialog in order to open the popUp. After loading the data, my goal is to open the popUp by using this porting method. import { mapState, m ...

Tips for displaying content when clicking on the opener containing tables or div elements

This is a snippet of JavaScript code $(document).ready(function () { $(".show-content").hide(); $(".opener").click(function () { $(this).parent().next(".show-content").slideToggle(); return false; ...

Tips for horizontally arranging a list with a flexible number of columns

I am attempting to create a horizontal list with 3 columns that automatically moves to a new line when the columns are filled. I have been trying to implement this using PHP but haven't had any success. If anyone could provide some guidance on how to ...

Exploring the bounds of self-invocation functions in JavaScript

Have you ever wondered why self-invocation functions inside another function in JavaScript don't inherit the scope of the outer function? var prop = "global"; var hash = { prop: "hash prop", foo: function(){ console.log(this.prop); ...

Issue with displaying the second dropdown based on the selection made in the previous dropdown

I wanted to address a recurring issue that has been discussed in various posts, such as this one on Stack Overflow: Show a second dropdown based on previous dropdown selection Despite attempting numerous solutions suggested in those posts, I have not been ...

Retrieve the file using React and receive it through Express

Despite trying several solutions on SO, none have been successful for me thus far, so I kindly ask for your patience. In React front-end, the user initiates a file download request with some variables to the backend: const data = text.value; fetch(" ...

Update the Laravel public directory

I need to update the public folder to public_html, but encountering issues with commands and functions still referencing the old public directory. While using Laravel+Vue for a single page application, my usual practice of renaming the public folder to pu ...

How can you efficiently pass multiple JSON files as arguments for Observable Arrays, especially when the values from one file are required for use in another file?

My goal is to utilize $.getJSON to retrieve data from two JSON files and assign their values to observableArrays. Currently, I have hard-coded the JSON data into the observableArray. You can view an example on this JSFiddle link. This was my initial appro ...