How can I eliminate unwanted zombie events in Vue JS?

How do you get rid of a zombie event?

When navigating back and forth, the events run multiple times.

MainApp.vue

<template>
  <input type="button" @click.prevent="handleClick()" value="Click Me">
</template>

<script>
export default { 
  methods: {
    handleClick: function (){
      this.$emit('go')
    }
  }
}
</script>

ChildComponent.vue

<script>
export default {
  methods: {
    go: function () {
      console.log('Event received')
    }
  },
  created: function (){
      this.$parent.$on('go', this.go);
  }
}
</script>

Answer №1

It is important to remember to remove the event listener when you are removing the component:

<script>
  export default {
    methods: {
      go: function () {
        console.log('event has been triggered')
      }
    },
    created: function (){
        this.$parent.$on('go', this.go);
    },
    beforeDestroy: function (){
        this.$parent.$off('go',this.go);
    }
  }
<script>

Answer №2

By including the click method in the created lifecycle hook, it ensures that the method will be called every time the children component is rendered.

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

Acquire data from an array of objects using JavaScript

I've written some code where I'm attempting to display certain values in HTML. Specifically, I am looking to extract the values from the "current" object: ("dt":1643884851, "temp":8.11, "description":"few clouds", and "icon":"02d") In addition, ...

Troubleshooting: Unable to preview Facebook Page plugin

When I visit the Facebook developer site to get the code for a Facebook page plugin, I use this link. The preview feature works perfectly with pages like "facebook.com/Nike", but when I try it with my own page, "facebook.com/BargainHideout", it doesn&apos ...

Alexa Skills Issue: Problem with Playing AudioPlayer HLS Stream URL

I'm currently using the "AudioPlayer" feature from the "Alexa Skill Kit" to stream an HLS audio format URL. No errors are showing up from AWS Lambda or the Developer Portal. I've been testing it with Silent Echo (). Alexa can play MP3 URLs and so ...

Is it more effective to import an entire library or specific component when incorporating it into Create-React-App?

I have a question about optimizing performance. I understand that every library has its own export method, but for instance, on react-bootstrap's official documentation, it suggests: It is recommended to import individual components like: react-boo ...

trouble with fetching data

Within my Backbone view, I have the following code snippet: var BookView = Backbone.View.extend({ initialize: function() { this.render(); }, render: function() { this.model.fetch({ success : function(model, resp, opt) { alert(this.$el. ...

Increase the progress bar at regular intervals of x seconds

I am looking for a jQuery UI progress bar that will increase by x amount every x seconds. Once it reaches 100%, I need it to trigger a function to retrieve some content. Essentially, I need a timer-like feature. EDIT: Note that I do not require any code ...

React compatibility problem with Internet Explorer 11

I'm encountering a problem with an error message stating "Expected identifier" in this code snippet. Any thoughts on what might be causing this issue? It seems like the problematic section of the code is originating from the transpiled version of th ...

Mastering the art of customizing modal input fields in Vue.js

I am currently working on a task manager app and I'm facing a problem. I want to be able to edit an existing task, but when I use v-model, the task edits instantly without the need for a save button. However, I do not want this behavior. I would like ...

Guide on storing images in a designated folder using CodeIgniter

My code is located in view/admin_view2.php <?php echo form_open_multipart('home_admin/createBerita'); ?> <div class="form-group" > <label class="control-label">upload foto</label> <inpu ...

Switch the view to a grid layout upon clicking

Using bootstrap 5, I've successfully created a list view: <div class="col"> Click to switch to grid/list </div> Below is the content list: <div class="row mt-3 list"> list view ... ..... ....... </div ...

The seamless union of Vuestic with Typescript

Seeking advice on integrating Typescript into a Vuestic project as a newcomer to Vue and Vuestic. How can I achieve this successfully? Successfully set up a new project using Vuestic CLI with the following commands: vuestic testproj npm install & ...

Transform JSON array containing identical key-value pairs

My array is structured as follows: [ { "time": "2017-09-14 02:44 AM", "artist": "Sam", "message": "message 1", "days": 0 }, { "time": "2017-09-14 02:44 AM", " ...

What steps should I take to address both the issue of duplicate names and the malfunctioning fixtures?

There are issues with duplicate item names and the cache not updating immediately after running the script. Instead of fetching new data, it retrieves previous values from the last item shop sections. If the remove_duplicates function is not used, it displ ...

Adjusting or cropping strokes in a JavaScript canvas

I am working with a transparent canvas size 200x200. The object is being drawn line by line on this canvas using the solid stroke method (lineTo()). I'm in need of making this object full-width either before or after ctx.stroke();. https://i.sstatic. ...

Adding x days to a Unix timestamp can be achieved by converting the Unix timestamp

Currently, I have the following code snippet: let currentTS = Math.floor(+new Date() / 1000) This code successfully retrieves the current date in a unix timestamp. However, my goal now is to append an additional 14 days to this unix timestamp. Could some ...

"Angular File Upload Made Easy with Drag-and-Drop Functionality and Cleverly Positioned

Encountering an issue with Angular File upload in conjunction with relatively positioned elements. The drop target is set to 100% width and height, absolutely positioned. While dragging a file over any non-relatively positioned element, the overlay functio ...

attempting to retrieve numerical variable beyond the function in jQuery

Trying to implement a star rating system and need to access the rating number for further actions. How can I make the number variable accessible outside of the click function? $(document).ready(function () { $(".li").mouseover(functio ...

Adjust Camera Position in A-Frame Scene Based on Scrolling Movement

I've been struggling to find a solution for this particular scenario in Aframe. I want to create an embedded Aframe scene as the background of a webpage and have the camera move along a path as the user scrolls down the page. I've set up a scene ...

Comparing values between two JSON objects in Angular 8: A guide

I need to compare the values of two objects, obj1 and obj2, by ignoring keys that are missing in either object. If all key-value pairs are equal, return false; otherwise, return true. For example: If 'id' is present in obj1 but not in obj2, it s ...

What's the best way to track changes in multiple form fields simultaneously in Angular?

Situation I have a form with 8 fields, but I want to monitor changes in just three of them to apply the same function. I don't want to set up individual subscriptions for each field like this: this.headerForm.get('start').valueChanges.subsc ...