When attempting to call a recursive method in Vue with a changing `this` object, an error is thrown: "RangeError: Maximum call stack size exceeded"

Update

integrate codePen into the project.

https://codepen.io/jiaxi0331/pen/xxVZBMz

Description

encountered an issue while trying to call the parent method recursively

Code

export default {
  methods: {
    dispatch(componentName, event, value) {
      if (this.$options.name === componentName) {
        this.$emit(event, value);
      } else {
        const parent = this.$parent || this.$root;
        return this.dispatch.call(parent, componentName, event, value); // Error. call this.dispatch in component.
      }
    }
    // broadcast(componentName, event, value) {}
  },

};

Expect && Detail Error

dispatch.call(parent) -> parent.dispatch.call(parent.parent) -> parent.parent.dispatch...

Detail error:

 Error in v-on handler: "RangeError: Maximum call stack size exceeded"

Version

vue 2.6.1

Try

function dispatch(componentName, event, value) {
  if (this.$options.name === componentName) {
    this.$emit(event, value);
  } else {
    const parent = this.$parent || this.$root;
    return dispatch.call(parent, componentName, event, value);
  }
}
export default {
  methods: {
    dispatch(componentName, event, value) {
      dispatch.call(this, componentName, event, value);
    }

    // broadcast(componentName, event, value) {}
  }
};

The workaround was successful. It was discovered that using dispatch.call(this.$parent) altered the 'this' object, leading to the failure of this.dispatch.call(this.$parent).

Answer №1

The problem lies in this specific line of code: this.$parent || this.$root. When a component does not have a parent, it is essentially at the root level, leading to potential infinite recursion if the component name is not present in the hierarchy.

When traversing up a tree towards the root, there are two possible end conditions: either the target node is located, or the root is reached without finding the target node...

dispatch(componentName, event, value) {
  if (this.$options.name === componentName) {
    this.$emit(event, value);
  } else if (!this.$parent) { // another ending condition - target not found
    this.$emit('not found');  // or any other action to prevent further recursion
  } else {
    return this.dispatch.call(this.$parent, componentName, event, value);
  }
}

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

Different ways to modify the CSS file of the bx-slider plugin for multiple sliders within a single webpage

Currently in the process of building a website using bx slider. I am looking to incorporate three sliders onto a single page for sliding HTML content. Initially, I added a bx slider to the page and customized it using CSS. I made modifications within jqu ...

An onClick event is triggered only after being clicked twice

It seems that the onClick event is not firing on the first click, but only works when clicked twice. The action this.props.PostLike(id) gets triggered with a delay of one click. How can I ensure it works correctly with just one click? The heart state togg ...

Encountering issues while attempting to pass a function into axios.then and catch and receiving errors

axios.post('http://localhost:3000/api/v1/login', { email: this.state.email, password: this.state.password }, { headers: { "Access-Control-Allow-Origin": "*", ...

AngularJS: Utilizing $http to fetch XML data instead of JSON

Looking to extract data from a website using angularjs / javascript. I am familiar with the $http object in angularjs which can make get requests. I have used it before to retrieve json, but I'm wondering if I can use it for XML (HTML) as well? (I th ...

Changing Marker Color in Google Maps API

There are multiple Google Maps Markers colors based on certain conditions being TRUE or not. In addition, these Markers will change color when the mouse hovers over a division (a1,a2..ax). I want the Markers to revert back to their original color when th ...

Choose2 incorporate on change

I have a Laravel project where I am using the vuexy theme. I've been trying to add an onchange event to my select2 input, but so far I haven't had any success. Here is my select2 input: <div class="col-12 mb-2"> <label class ...

Having trouble with Node.js executing commands in the console

I've been following some tutorials on YouTube to learn how to create a real-time chat using Node.js from the phpacademy channel. Currently, I'm stuck at the step where I need to run my server.js file in the console. When I enter the command ...

What could be causing the error when trying to submit to OData Edm.Decimal type?

Having an issue submitting JSON to an OData service. The $metadata indicates it expects this format: <Property Name="curClaimValue" Type="Edm.Decimal" Nullable="true" Precision="19" Scale="4"/> This snippet is from my JSON data: ..."curClaimValue" ...

Load a script in a specific div using React

Can anyone assist me with loading a script onto a specific component in my React application? Here is the script that needs to be loaded at the bottom-most div within my component: <div id="rexxxx"></div> <script> new carouselI ...

What causes data to be undefined when sending it to PHP through AJAX?

this is the javascript code snippet I wrote var ActivityType ='d'; var TotalActivities = 2; function marker(ActivityType,TotalActivities) { var dataTosend='typ='+ActivityType+'&total='+TotalActivitie ...

What is the best way to create a collage of images with a random and unique arrangement?

Recently, I stumbled upon a website and was intrigued by the unique effect of images randomly appearing on the screen. I'm curious about how this effect can be achieved. Is it possible to use CSS Grid to divide the screen and designate some grid ite ...

What is the reason behind V8's perplexing error notification?

When running this code on Chrome or Node (v8), an error message is displayed: Uncaught TypeError: f is not iterable function f(){} f(...undefined); Why is such an ambiguous error message generated in this case? Does it really have nothing to do with ...

Bring in the component along with its attributes and functions into another component

Suppose I have a component called LogoutButton.vue export default { data() { return { } }, methods: { Logout() { console.log("something") } } } </script> <template> <button ...

Tips for exporting an array of dynamic JSON objects to CSV using Angular

I am facing a challenge in exporting an array of JSON objects to CSV as the number of key-value pairs can vary, leading to additional columns in some objects. Currently, I am using the Angular2CSV package for export functionality, but it requires all colum ...

Managing JavaScript with Scrapy

Spider for reference: import scrapy from scrapy.spiders import Spider from scrapy.selector import Selector from script.items import ScriptItem class RunSpider(scrapy.Spider): name = "run" allowed_domains = ["stopitrightnow.com"] start_urls = ...

Problems with implementing JavaScript code in a WebView

I am currently working on an android WebView project where I have managed to change the background color to orange with this code snippet. @Override public void onPageFinished(WebView view, String url) { wv.loadUrl("jav ...

Ways to conceal buttons according to your 'occupation'?

I am currently developing an application and I would like to have certain buttons displayed based on the user's $job. There are four job roles stored in mysql databases: student teacher staff principal, The signup button should only be visible to te ...

HTML/PHP/JS - Submit Form and Upload File Simultaneously

I need to create a form with a Photo Upload Input that allows users to upload pictures before submitting the form for faster processing. The form should also support uploading multiple files, display a progress bar, and provide a preview of the uploaded im ...

What is the object pattern in Typescript?

Recently delving into TypeScript, I am eager to learn how to define an interface for the following type of object: const branch = { 'CN': { 'name': 'CN Name', 'branch': 'Chinoise', 'url& ...

Unlocking the Power of Combining JMVC and Server-side MVC Models

It's been a few days since I posted this question here and still no response. I also tried posting it on forum.javascriptMVC.com and finally got an answer, but I'm looking for more insights. Here's my question: After reading the documentat ...