Repetitive occurrences of events being emitted from a VueJS component

As my mouse cursor hovers over and exits my VueJS component, specific methods are triggered accordingly.

The methods that execute when the cursor enters and leaves my component:

// Included in the "methods" section of my Vue component file

onMouseEnter() {
    window.Event.$emit("mouse-entered", this.index);
    console.log("Mouse entered");
},
onMouseLeave() {
    window.Event.$emit("mouse-left", this.index);
    console.log("Mouse left");
},

Upon hovering and exiting the component, individual events get emitted as seen in my console:

https://i.sstatic.net/oqa1O.png

Yet, a peculiar occurrence arises within Vue dev tools showing duplicated events with each hover and exit on the component:

https://i.sstatic.net/I9sWo.png

This conflicting scenario leads to uncertainty. While refreshing the page may sporadically resolve the duplicates in dev tools, the console consistently displays single, distinct events - which aligns with the intended behavior.

Can anyone provide insight into this situation and clarify the valid source of truth?

Below is the setup for declaring and initializing my Vue instances in main.js:

// I haven't identified any duplicated Vue instances created upon page refresh

let app;

// Global event bus
window.Event = new Vue();
console.log("Event bus created");

/* This code segment ensures the firebase auth object maintains its state */
firebase.auth().onAuthStateChanged(() => {
    if (!app) {
        console.log("New Vue instance created");
        app = new Vue({
            el: '#app',
            router,
            store,
            render: h => h(App)
        });
    }
});

Note that this specific component is utilized on two different routes ("dashboard" and "home"), both sustained by this caching mechanism.

// Template excerpt from App.vue file
<template>
    <div id="app">
        <keep-alive
            v-bind:include="[ 'dashboard', 'home' ]"
            <router-view></router-view>
        </keep-alive>
    </div>
</template>

In addition, given the persistent nature of the cached routes, it's unlikely that failure to deactivate event emitters and listeners is causing the duplication issue (or so I believe).

EDIT 1: Through a thorough search for "mouse-entered" and "mouse-left" across all project directories, I can confirm these events solely originate from the referenced Vue component.

EDIT 2: To aid in diagnostics, I attached a listener to my top-level component (App.vue) to observe potential double event reception (referencing the created hook in the code below). It indeed only captures the event once. The complete App.vue file is included to underscore the role played by "dashboard" and "home" components.

<template>
    <div id="app">
        <keep-alive
            v-bind:include="keepAlive">
            <router-view></router-view>
        </keep-alive>
    </div>
</template>

<script>
    export default {
        name: 'app',
        data() {
            return {
                isLoggedIn: false,
            };
        },
        computed: {
            keepAlive() {
                if (this.isLoggedIn) {
                    return [ 'dashboard', 'home', 'results' ];
                }
                return [ 'landing', 'signIn', 'signUp' ];
            }
        },
        watch: {
            /* Watches for changes in route */
            $route(to, from) {
                /* firebase.auth().currentUser returns null post logout */
                if (firebase.auth().currentUser) {
                    this.isLoggedIn = true;
                } else {
                    this.isLoggedIn = false;
                }
            }
        },
        created() {
            window.Event.$on("mouse-entered", () => {
                console.log("mouse-entered-from-App.vue");
            });
            window.Event.$on("mouse-left", () => {
                console.log("mouse-left-from-App.vue");
            });
        }
    };
</script>

Indeed, App.vue acknowledges the event once (as depicted); nonetheless, the issue of duplicate events persists within Vue dev tools :(

https://i.sstatic.net/VIV3e.png

Answer №1

Your message states that refreshing the page can sometimes resolve the issue of duplicate events appearing in dev tools, while single unique events are consistently displayed in the console, which is the desired outcome.

However, it seems like the problem lies not with the emission of events but rather with how they are being handled and reacted to - resulting in duplicates.

To address this issue, it may be necessary for you to unsubscribe from the event bus once the component is destroyed. This can be achieved by implementing the use of the beforeDestroy hook, similar to how you subscribed using the created hook at an earlier stage in the component's lifecycle.

You can include the following code snippet:

beforeDestroy() {
    window.Event.$off('mouse-entered');
    window.Event.$off('mouse-left');
}

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

Tips for retrieving JSON data from an AJAX call and displaying it pre-filled in an input field

Here is the code snippet I used to receive a response in JSON format, but when I try to display the response using alert(response.Subject);, it shows as "undefined". HTML: <input type="text" id="subject" value='Subject'> Javascript: $.a ...

Use two fingers to scroll up and down on the screen

I am currently developing a sketch web application (using angular) that utilizes one finger gestures for drawing. My goal is to enable vertical scrolling in the sketch content by using two fingers. However, when attempting to scroll with two fingers, Safa ...

The function queryDatabases is not supported in the DocumentDB JavaScript API

Currently, I am developing a service for Azure Functions using JavaScript/Node.js. However, I encounter an error when trying to access the function DocumentClient.queryDatabases. Despite having the correct references installed in Visual Studio Code and bei ...

Transforming JSON data into XML using Angular 7

It turns out the xml2js npm package I was using doesn't support converting JSON to XML, which is exactly what I need for my API that communicates with an application only accepting XML format. In my service file shipment.service.ts import { Injecta ...

Tips for interpreting the JSON data returned by a Node server in Angular

When trying to implement a login form in my Angular frontend, I encountered an issue with reading the JSON object returned from my node.js server. Despite following the correct steps, the console displays "undefined" as if it cannot recognize the format. ...

Using the jquery slider in conjunction with the onchange event

I have integrated a jquery slider add-on into my project that updates a value in a Linux file whenever it is manipulated. The slider is connected to a text input box, which is set as readonly and therefore always blurred. The issue I am facing is that the ...

The event.pageY position consistently reflects the laptop screen size rather than the exact position where the click occurred

My webpage is scrollable, but the event.pageY position always corresponds to my screen size. Even when scrolling down and clicking near the top of the screen, it registers as 50px. I am currently utilizing event.pageY While this functions correctly on a ...

The set interval function in JavaScript does not properly call PHP in Internet Explorer

I'm currently implementing code to display the updated message from the database. Here is what I have so far: var showtime = setInterval('redirect()',5000); ////Redirecting to DB Status ///// function redirect() { xmlhttp = GetXmlHttpOb ...

Using Jquery to hide or show objects within a <div> when clicked

My goal is to create a webpage that displays three different contents based on which button is clicked. Below is the code for reference: I want the page to show three specific sections: A search bar only when the 'search' button is clicked, T ...

How can I implement SSO and Auth for multiple sub-domains using PHP?

Is it possible to implement SSO using PHP between two different sub-domains (e.g. parappawithfries.com and *.parappawithfries.com)? My current configuration is causing issues as I use Cloudflare to direct my subs to a different 000webhost website. While I ...

Executing mathematical operations with floating point numbers using JavaScript in Python

I’m creating a Python program that interacts with a web application that I didn’t develop. There is some data that needs to be represented in my program which isn’t directly sent to the client by the server, but is instead calculated separately on bo ...

The challenge with encoding URL in Ajax requests

I am trying to send an encrypted message along with the corresponding key (two-way encryption) to a PHP page for decryption, and then receive the decrypted result in the response. Below is an example of how I am attempting to send the encrypted message us ...

Utilizing Axios Response Data in the Data Function of Vue Components

Utilizing axios for fetching API data: fetchData () { axios.get(globalConfig.OFFERS_URL) .then((resp) => { this.offersData = resp.data console.log(resp) }) .catch((err) => { console.log(err) }) } Data method defi ...

The process of implementing server-side rendering for React Next applications with Material-ui using CSS

I have developed a basic React application using Next.js with an integrated express server: app.prepare() .then(() => { const server = express() server.get('/job/:id', (req, res) => { const actualPage = '/job' const ...

How can Swiper efficiently display the next set of x slides?

After exploring SwiperJS at https://swiperjs.com/, I've been unable to locate an option that allows the slide to return immediately to the right once it goes out of view on the left. The current behavior poses a problem where there is no next slide o ...

What is the best way to implement variable scope when using a callback function in AngularJS

I'm facing a major issue in my AngularJS application. I have a factory module with an getAll() function that retrieves JSON data from the server. In the controller module, I attempt to assign the value returned by the factory's getAll() function ...

What steps are involved in enabling Server Side Rendering with Next.js?

For my exploration of Next.js, I started by setting up a new Next.js project and incorporating code to retrieve weather data: export default function Home() { const [data, setData] = useState(null); useEffect(() => { fetch("https://api.we ...

The value retrieved by JQuery attr remains constant

Hey everyone, I'm having an issue with getting the ID from a custom attribute using jQuery. When I try to debug, I keep getting the same value each time. I have an HTML table that lists posts from a database using PHP, each with its own specific ID. ...

Discover the method for invoking a Javascript function within a Leaflet popup using HTML

Upon clicking on a marker on the leaflet map, I aim to trigger a popup box that contains five elements: Title Description Image Button (Next Image) Button (Previous Image) To achieve this, I attempted to include a custom popup for each feature ...

Unable to retrieve the following element in a JavaScript array

I am a beginner in JavaScript and I am attempting to access the next element of an array using an onclick function but so far I have not been successful. var i, len; function quiz() { var quiz_questions = [ "who is the founder of Fa ...