Why does the old component of the router still receive and handle events when <router-view/> changes?

Ugh... I need to explain a tricky situation I'm facing. I have a parent component that has two children listening for the same event and performing similar actions (see code snippet below):

mounted() {
 EventBus.$on('edit', (data) => {
  console.log('service called')
  this.showRightSide(data)
 })
},

showRightSide(data) {
  console.log(data)
  // display right-side operator edit page.
  this.$store.commit({
    type: 'setShownState',
    shown: true
  })
  // giving operator name & operator type
  this.$store.commit({
    type: 'setOptName',
    optName: data.name
  })
  this.$store.commit({
    type: 'setOptType',
    optType: data.type
  })
},

Incorporating the vue router adds complexity:

{
  path: '/main',
  name: 'Main',
  component: Main,
  children: [
    { path: 'service', name: 'Service', component: ServiceContent },
    { path: 'model', name: 'Model', component: ModelContent }
  ]
},

Shouldn't there be three commits during each 'edit' event?

Initially, there are indeed 3 commits.

However, when switching from '/main/service' to '/main/model', it triggers 6 commits during each 'edit' event (the old ServiceContent component still makes 3 commits and the new ModelContent component contributes another 3).

Returning to '/main/service' results in 9 commits!!!

Devtool screenshot:

It appears that even after the router-view changes, the old view's component can still receive events. How do I resolve this? (EventBus is simply a global vue instance serving as an event bus)

Answer №1

When you invoke the $on() method, Vue internally registers your callback function as an observer. This ensures that your function continues to operate even after the component is unmounted.

Remember to use the $off method when your component is being unmounted.

Here's an example:

methods: {
  displayInfo (data) {
    // etc
  }
},
mounted () {
  EventBus.$on('update', this.displayInfo)
},
beforeDestroy () {
  EventBus.$off('update', this.displayInfo)
}

Answer №2

To ensure proper cleanup of listeners, it is recommended to manually handle this in the beforeUnmount function. It's important to note that due to how JavaScript handles garbage collection, Vue may not automatically clean up externally referenced items like listeners.

methods: {
  handleEventBusEdit(data) {
    console.log('service called')
    this.showRightSide(data)
  }
},
mounted() {
 EventBus.$on('edit', this.handleEventBusEdit)
},
beforeDestroy() {
  EventBus.$off('edit', this.handleEventBusEdit)
}

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

Ways to tally elements that have been dynamically loaded onto the webpage through AJAX requests

My page has a dynamic region that is continuously updated using jQuery's .ajax and .load methods. In order to submit the form, there need to be at least 3 of these 'regions', so I have to keep track of the number of DIVs with a specific cla ...

Issue with CORS Policy specifically in this scenario despite functioning properly for other assets

My API is built with Laravel and for the front-end, I am using Vue.js with Nuxt.js. I have successfully installed the CORS policy package, which is working well with all my other resources. However, I encountered an error for one of my features: ...

I'm looking for a way to implement a jQuery-style initialization pattern using TypeScript - how can I

My library utilizes a jQuery-like initialization pattern, along with some specific requirements for the types it should accept and return: function JQueryInitializer ( selector /*: string | INSTANCE_OF_JQUERY*/ ) { if ( selector.__jquery ) return select ...

Tips on updating the arrow icon after clicking on a dropdown menu

HTML: <div class="customSelectContainer"> <ul> <li class="initial">Choose</li> <li data-value="value 1">Option 1</li> <li data-value="value 2">Option 2& ...

Unable to declare a string enum in TypeScript because string is not compatible

enum Animal { animal1 = 'animal1', animal2 = 'animal2', animal3 = 'animal3', animal4 = 'animal4', animal5 = 'animal5' } const species: Animal = 'animal' + num Why does typescr ...

Which specific event in NextJS is triggered only during the initial load?

I am working on a NextJS app and I want to implement an initial loading screen that only appears during the first load. Currently, the loading screen pops up not only on the initial load but also whenever a link is clicked that directs the user back to the ...

What steps can be taken to avoid including empty tasks in React code?

Is there a way to prevent my application from adding empty tasks? Below is the code snippet for adding a new task to an array. How can I implement a condition to block the addition of empty tasks? This application follows Mozilla's guidelines for a R ...

How can we transfer a jQuery value from an input field without using a single

This task may seem challenging. How can single quotes be eliminated from a variable when passed directly to another variable? I am using jQuery variable $("#test").val() to extract the value from an input below <input type="text" ...

Issues with utilizing Jquery datepicker within a Vue.js component's v-for loop in Laravel

I am facing an issue with the Jquery date picker inside a v-for loop in my vue.js component. The date picker works fine outside of the loop, but inside the loop it does not behave as expected. Here is a snippet of code where the date picker is working cor ...

Submenu animation that "bursts onto the scene"

I'm facing an issue with my menu that has sub-items inside it. To achieve the animation effect I desire, I need to extract the width, height, and first-child's height of the sub-menu. While my animation is working most times, there are instances ...

Tips for updating the checkbox state while iterating through the state data

In my component, I have the ability to select multiple checkboxes. When a checkbox is selected, a corresponding chip is generated to visually represent the selection. Each chip has a remove handler that should unselect the checkbox it represents. However, ...

Setting up Webpack for react-pdf in a Next.js application

In my Next.js application, I am utilizing the react-pdf library to generate and handle PDF files on the client side without involving the server. However, I am facing challenges in setting up Webpack for Next.js as I lack sufficient expertise in this area. ...

Error occurs when attempting to change the color of a dynamically generated div, resulting in the message: "Type Error: Unable to assign a value to the property '

I'm facing an issue with my code where I have a parent div that loads with a random color, and upon clicking a button, it should create a new colored div inside. However, I keep encountering the following error: TypeError: Cannot set property ' ...

Promise and Determination failing to produce results

const { GraphQLServer } = require('graphql-yoga'); const mongoose = require('mongoose'); mongoose.connect("mongodb://localhost/test1"); const Todo = mongoose.model('Todo',{ text: String, complete: Boolean }); const ...

Altering the "src" property of the <script> tag

Can the "src" attribute of a current <script> element be altered using Jquery.attr()? I believed it would be an easy method to enable JSONP functionality, however, I am encountering difficulties in making it operate effectively. ...

The test does not pass when attempting to use a shorthand operator to ascertain the truthfulness of

I've encountered an interesting issue with my unit test. It seems to work perfectly fine when I directly return true or false, but fails when I try to use a shorthand method to determine the result. Let's say I have a function called isMatched w ...

What is the correct way to fetch JSON data from a remote server using pure JavaScript?

I'm receiving JSON data from a remote server at openweathermap.org. Can anyone help me identify issues with my code? Here is an example of the server's response here var getWeatherJSON = function (city) { var httpRequest = window.XMLHttpRequ ...

React.Js custom form validation issue in Next.Js - troubleshooting required

My attempt at validating a form is causing some issues. After refreshing the page and clicking on the submit button, only the last input's error is generated instead of errors for every input according to the validation rules. Here is a screenshot o ...

Detaching jQuery event listeners

Suppose I have two event handlers of the same type attached to the same object. The following example shows the mousemove event being attached to the window object. $('body').on('mousedown', '#uiScrollbar', function(e) { v ...

What is the best way to conceal a specific class of DIV within a container, and how can I also hide another DIV within the same container by

I have a DIV class containing around 10 elements within a container. I am looking to implement a feature where these elements are hidden and shown one by one every 15 seconds using jQuery with a smooth fadeOut() effect. Your assistance in achieving this wo ...