Find all the components associated with a specific name in Vue, even if they are nested within other components

One interesting feature in my app is the sidebar:

https://i.sstatic.net/7Z9IN.png

The code for the tree item component looks like this :

 <!-- tree item template -->
 <script type="text/x-template" id="tree-item-template">
    <div>
        <div>
            <user-card @toggle-supervisor="toggle" :user_info="item" :key="item.id_user"></user-card>
        </div>
        <div v-show="isOpen" v-if="isFolder" class="ml-3">
            <tree-item
            v-for="(child, index) in item.employees"
            :key="index"
            :item="child"
            ></tree-item>
        </div>
    </div>
</script>

This component has a nested component named user-card.

I am aiming to create an array containing all components with the name 'user-card', irrespective of nesting within other components.

This is required so that I can change the color of the name to blue when selected (clicked) and back to black when deselected.

I have discovered that using this.$children allows me to fetch a list of components within a component, but not all of them. Therefore, I am exploring if there is a way to retrieve a list of all elements based on their component name.

Answer №1

To easily gather all user cards in your Vue component, you can utilize the following code snippet:

        const children = this.$children.slice();
        const userCards = [];
        let currentChild;

        while (children.length > 0) {
          currentChild = children.shift();
          
          if (currentChild.$options.name === 'user-card') {
            userCards.push(currentChild);
          } else {
            const grandchildren = currentChild.$children.slice();

            for (let i = 0; i < grandchildren.length; i++) {
              children.push(grandchildren[i]);
            }
          }
        }

        // The "userCards" array now contains all user cards from the original component

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

What steps can be taken to avoid special characters in ion-input fields?

When inputting special characters into the field used for storing the alphanumeric serial number, they are accepted. I need to prevent special characters from being entered in the input field. <ion-input [(ngModel)]="serial_number" (ngModelCha ...

End the basic JavaScript slideshow after completing one rotation

I have limited knowledge of JavaScript, but I am in search of a simple solution for a code that I want to implement. I don't need any fancy transitions or effects, just a basic slideshow that switches between images. My goal is to have the slideshow p ...

What is the best way to execute fetch calls in sequence (A -> B -> C) within a React component?

I'm facing an issue with three fetch functions - a(), b(a_id), and c(b_id). The flow is such that function a returns an a_id which is then passed to function b, and b in turn returns an id passed to function c. componentDidUpdate(prevProps) { this ...

Challenge with jQuery - updating closest HTML element not functioning as expected

A script was created to extract the innerHTML of an element with a specific class. Initially, this worked perfectly for the first <table>, but the same script applied to table 1 is affecting the second and third <table> as well. An attempt was ...

Is there a way to automatically compress Express JS assets?

Is there a way to dynamically minify the frontend JavaScript/CSS of my Express JS application? Are there any potential drawbacks to this approach? ...

What steps can I take to ensure this conversion meets markup validation requirements?

I keep encountering a validation error that keeps coming up: $("#preview").html('<div align="center"><img src="/ajaximage/loader.gif" alt="Uploading...."/></div>'); The error message states: document type does not allow elemen ...

It is not possible to utilize a JavaScript function once the script has been loaded through

I am attempting to programmatically load a local JavaScript file - PapaParse library, and then utilize one of its functions: $.getScript("./Content/Scripts/papaparse.js", function () { console.log("Papaparse loaded successfully"); Papa.parse(file, ...

SweetAlert2 not displaying properly in Ionic6 - troubleshooting the issue

My current project is an Ionic 5 Angular project with SweetAlerts2 popups. Recently, I decided to upgrade to Ionic6 and encountered an issue where the SweetAlerts2 popups are not displaying correctly. The alert seems to only show up in the header, leaving ...

Store a function as a variable in AngularJS

My goal is to dynamically call a function based on a variable that holds the function name. For instance: var fun =function1(1,2) Then later, fun could be assigned another function: fun= function2(2,3) This is just an example to illustrate my situation ...

Refreshing Yii Dropdown List After Adding a New Item

Here is the code snippet I am working with: <p> <?php echo $form->labelEx($model,'phone_type'); ?> <span class="field"> <?php echo $form->dropDownList($model,'phone_type', CHtml::listData(PhonesT ...

When working with Vue.js, toggling the 'readonly' attribute of a textarea between true and false may not be effective

My goal is to accomplish the following: Allow the textarea to be edited when double-clicked; Prevent the textarea from being edited when it loses focus; However, regardless of toggling the 'readonly' attribute, I am currently unable to achieve ...

Angular proxy - Syntax error found in proxy configuration file: proxy.conf.json

My Angular 6 setup is configured to make HttpRequests, but I encountered a problem that requires me to run them through a proxy. To address this issue, I created a proxy.conf.json file next to my package.json: { "/loans/": { "target" : "https://api. ...

How can we transfer parameters in JavaScript?

My vision may be a bit vague, but I'll try to explain it as best as I can. I want to implement multiple buttons that can toggle the visibility of a div (I have this functionality working already). Each button should carry two values (a number and a l ...

Regularly updating a book's interactive pages with turn.js technology

I experimented with generating dynamic content in turn.js using the sample provided here. This is an excerpt of the code I have written: <body> <div id="paper"> </div> </body> <script type="text/javascript"> $(win ...

Adding an object to a document's property array based on a condition in MongoDB using Mongoose

I have a situation where I need to push an object with a date property into an array of objects stored in a MongoDB document. However, I only want to push the object if an object with the same date doesn't already exist in the array. I've been e ...

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 ...

Utilize the keep-alive feature to cache a single route component dynamically

I am working on conditionally setting the keep-alive feature for some of my route components. I want to be able to clear the cached routes and set new ones when necessary. The code I have written below is functional, but I am facing an issue with clearing ...

Learn how to navigate to a different page in vuetify after a successful password validation

To direct the user to the "customers" page only if the password entered in this form is correct, display an error message otherwise. <v-card-text> <v-form> <v-text-field id="password" label= ...

Explore RxJs DistinctUntilChanged for Deep Object Comparison

I have a scenario where I need to avoid redundant computations if the subscription emits the same object. this.stateObject$ .pipe(distinctUntilChanged((obj1, obj2) => JSON.stringify({ obj: obj1 }) === JSON.stringify({ obj: obj2 }))) .subscribe(obj =& ...

Send a pair of values using a set of two parameters

My current code is currently passing only one parameter value. However, I would like to modify it to pass two values with two parameters. This is my current code: <script> function getfilter(str){ document.getElementById("result"). ...