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:

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

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

Having difficulties accessing information from the HTML document

I face an issue with my code where I am unable to fetch the sectionID from tr. I want to retrieve the dynamic id of sectionID on each button click for deletion, but it always returns null. Below is the JQuery script: <script> $(function () { $(&apo ...

The functionality of Node.js middleware is not functioning correctly

My module contains Routes, and I want to verify access before allowing users to proceed. Within the Routes module, there are two routes and two access-check functions that I want to use as middlewares: const checkUser = (req, res, next) => { if (!us ...

Convert checkbox choices to strings stored in an array within an object

I have a intricate object structure JSON{ alpha{ array1[ obj1{}, obj2{} ] } } In addition to array1, I need to include another array: array2 that will only consist of strin ...

Utilizing Vue to Embed Multiple Hubspot Forms on one Page

While working on a Vue page, I encountered an issue with loading multiple Hubspot forms simultaneously. Only one form would load at a time. Here is the code snippet I used to append a single Hubspot form: mounted() { const script = document.createElem ...

Using `href="#"` may not function as expected when it is generated by a PHP AJAX function

I am facing an issue with loading html content into a div after the page has loaded using an ajax call. The setup involves a php function fetching data from the database and echoing it as html code to be placed inside the specified div. Here is my current ...

JSON to URN Converter: A tool for converting JSON references

Is there a way to convert URL references to JSON and back again programmatically? (include:(and:List((or:(urn:li:adTargetingFacet:locations:List(urn:li:geo:102221843)) ),(or:(urn:li:adTargetingFacet:skills:List(urn:li:skill:17)))))) Are there any JavaScri ...

Using Node.JS, Sequelize, and Moment.JS to format dates

Seeking help on formatting a date loaded from Sequelize in my database. I'm working on a blog and need to display the creation date of an article. Here's my route: app.get("/", (req,res) =>{ Article.findAll({ order:[ [ ...

Using jQuery to retrieve the HTML code for links

I am looking for a way to extract HTML links from a specific div without relying on regular expressions. Here is an example scenario: <div>Please review the links provided in the content. For instance, <a href="http://en.wikipedia.org/wiki/Apple ...

Comparing angular.isDefined and typeof

Is there an angular equivalent to the typeof operator in JavaScript that can detect variables not defined? I am specifically interested in the behavior of angular.isDefined() and how it differs from typeof. In the example below, the variable x is not Defin ...

Steps for setting up the mongodb package in a vue/nuxt application

I am having trouble getting the example below to work inside a VUE component or in the middleware. The backend consists of VUECLI and NUXT. This code snippet works for NodeJs, but I can't seem to make it function properly in my setup. // Connection t ...

`The header navigation is not responding to window resizing functionality`

I am currently developing a header navigation that consists of a logo on the left side, a profile icon on the right side, and some navigation links in the middle. A left slide menu has been implemented to trigger when the window width is less than 700px. ...

Refreshing MongoDB data by utilizing values from an object

I am facing a challenge with my MongoDB collection structure: [ { "stock": "GOOGLE", "price": 0 }, { "stock": "FACEBOOK", "price": 0 } ] On the other hand, I have a Stock_P ...

Switch out "FOR" in order to sum up every value within an array

Utilizing Javascript, I have an array defined as follows: counts: [ { id: 1, value: 0 }, { id: 2, value: 10 }, { id: 3, value: 5 }, { id: 4, value: 3 } ] I aim to calculate a variable named total that holds the sum of all valu ...

Encountering an issue with finding the module `scheduler/tracing` in React Native

Encountering an error during the react-native run-android process: Error: Unable to resolve module `scheduler/tracing` from `/Users/miftahali/projects/react/appscustomec/node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js`: Module ...

Requirements for using Angular JS and Node JS

With upcoming projects involving AngularJS and Node.js, I'm a bit apprehensive as I don't have much experience with JavaScript. Should I start by picking up a book on each technology, or is it essential to learn more about JavaScript first before ...

Having difficulty asserting the dual-function button in both its disabled and enabled states

I have a button that is part of a dual-action setup. This button is disabled until a certain event occurs. Here is the DOM structure while the button is disabled: <div class="doc-buttons"> <a href="#" onclick="actualsize();" id="tip-size" cla ...

Returning data to be displayed in Jade templates, leveraging Express and Node.js

Yesterday, I had a question. Instead of using next() and passing an Error object, I decided to figure out what it was doing and replicate it. So now, when someone logs in and it fails, I handle it like this: res.render("pages/home", { ...

I am looking to efficiently store various pieces of data in a database by utilizing a singular variable through JS, PHP, and AJAX for streamlined processing and management

I am not very familiar with the technical jargon in programming, so please bear with me if my question is a bit unclear. To provide more clarity, I have shared the code that I have already written. I will elaborate on the issue after presenting the code: ...

Sending javascript data to php within a modal popup

I am currently working on passing a javascript variable to php within a modal window, all while remaining on the same page (edit.php). Although I plan to tackle handling this across separate pages later on, for now, I have successfully implemented the foll ...

Can Browserify be used with AngularJS to bundle directive templateUrls using relative paths?

Currently, I am developing a web application using AngularJS and Browserify to bundle my JavaScript files into a single package for use on the webpage. My project structure looks something like this: app |-index.html |-index.js |-bundle.js |-components ...