Is there a way to ensure my Vue variable is declared once the page has fully loaded?

I have implemented a v-for loop in my code:

<div v-for="(user, index) in users" :key="index" :presence="user.presence" class="person">
     <span class="cardName h4">{{ user.name }}</span>
</div>

I declared a variable people to store all created elements. Surprisingly, it worked in one function but not in another.

Upon investigating further, I discovered that the variable is empty in the second function. I attempted creating a single variable for both functions, but encountered issues as the variable cannot be initialized until the page has rendered (even using lifecycle hooks didn't resolve the problem).

filterByName () { // this function is functional
    const people = document.querySelectorAll(".person")
    
    console.log(people.length) // returned correct number
    console.log("Sorting by name")
            
    for (let i = 0; i < people.length; i++) {
        let inner = people[i].getElementsByClassName("cardName")[0].innerHTML

        if (inner.toUpperCase().indexOf(this.sortName.toUpperCase()) > -1) {
            people[i].style.display = ""
        } else {
            people[i].style.display = "none"
        }
    }
},
filterByPresence() { // this function does not iterate through any loops
    const people = document.querySelectorAll(".person")
    
    console.log(people.length) // returns 0
    
    if (this.filterMode == 0) {
        console.log("Filtering by lack of presence")
        
        for (let i = 0; i < people.length; i++) {
            if (!people[i].getAttribute("presence")) {
                people[i].style.display = ""
            } else {
                people[i].style.display = "none"
            }
        }
        
        this.filterMode = 1;

    } else if (this.filterMode == 1) {
        console.log("Filtering by presence")
                
        for (let i = 0; i < people.length; i++) {
            if (people[i].getAttribute("presence")) {
                people[i].style.display = ""
            } else {
                people[i].style.display = "none"
            }
        }

        this.filterMode = 2;

    } else if (this.filterMode == 2) {
        console.log("Showing all")

        for (let i = 0; i < people.length; i++) {
            people[i].style.display = ""
        }

        this.filterMode = 0
    }
}

So, my main query is: Why does one function work while the other doesn't, and what steps can I take to ensure they both function correctly?

Answer №1

It seems like there might be a need for more information on how exactly you are utilizing these two functions. Typically, they are designed to only function properly within the mounted hook, so please double check this aspect.

Also, since you have generated these elements using users, it could be simpler to just utilize this.users instead of creating a new constant like const people. Additionally, consider using v-show to manage the display style. If this.users is not part of your current component, you may want to explore using props or Provide/Inject or frameworks like pinia/vuex. Modifying the document directly might lead to unforeseen issues.

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

Tips for concealing a dynamic table element in Angular 9

I have dynamically generated columns and rows in a table. Here is my HTML for the table component: <table id="tabella" class="table table-striped table-hover"> <thead class="thead-dark"> <tr> <th *ngFor="let header of _ob ...

Button click causing TextField to print incorrectly

I am working on implementing a feature in my react application where users can input a search term, and upon pressing the button, it will be used to perform a search. The text input field and button are utilizing material-ui components. At this stage, I si ...

Executing a function right away when it run is a trait of a React functional component

Having a fully functional React component with useState hooks, and an array containing five text input fields whose values are stored in the state within an array can be quite challenging. The main issue I am facing is that I need to update the inputfields ...

Can dynamic loading JavaScript be debugged using a debugger such as WebKit, FireBug, or the Developer Tool in IE8?

After asking a question on Stack Overflow, I have successfully written JavaScript functions for loading partial views dynamically. However, debugging this dynamic loading script has been a challenge for me due to all loaded JavaScript being evaluated by th ...

Display corresponding div elements upon clicking an HTML select option

Is there a way to make a div visible when a corresponding select option is clicked, while hiding others? My JavaScript skills are lacking in this area. CSS #aaa, #bbb, #ccc { display:none; } The HTML (I'm using the same id name for option and d ...

What is the best way to extract value from a JSON object with jQuery?

How can I retrieve the value of 'FRI' from the JSON feed returned by an AJAX call using jQuery? $.ajax({ url: query, type: "GET", dataType: "json" success: function(data) { var day = // extract data value from JSON ...

Calculating the median in JavaScript utilizing a for loop

Currently, I am in the process of learning JavaScript. My goal is to calculate the median of a set of numbers that I input through a prompt when I click the button labeled "find median". function CalculateMedia() { var n = prompt("Enter the number of e ...

"Looking to retrieve data from an array instead of an object in JavaScript? Here's how you can

There is a slight issue with my fetch method in grabbing data from this link . I am attempting to use the .map function on it but instead of functioning properly, I encounter an error that says Unhandled Rejection (TypeError): jedis.map is not a function. ...

Looking for ways to detect memory leaks in your JavaScript application using Selenium?

While utilizing Java and Selenium for automated testing of a JavaScript web application, the issue of memory leaks has arisen. I am interested in ways to effectively test for them. Is there a simple method to obtain memory usage and other profiling data fo ...

Error message displayed when the date is null in the Vue-good-table: "Invalid Date

I'm currently working with the vue-good-table table component for Vuejs which allows you to easily format your columns as strings, numbers, or dates. Today, I encountered an issue specifically regarding date formatting. While I can successfully forma ...

Add the hue value from Hue into the Chromajs HSL state value

My objective is to dynamically change the background color of a div based on user input. I plan to assign the user's input as the value of the state key hue, and then set another state key called color to hold the HSL representation of the hue using C ...

In Cypress, I am trying to specifically choose only numerical values from a dropdown menu. However, the list contains a mix of alphanumeric and numeric values

Looking to streamline: This is my code: cy.get('[role=presentation]') cy.get('[role=row]').find('td') .get('[role=gridcell]').eq(9).click().wait(2000) cy.get('[role=listbox]').get('[role=option]& ...

Webpack and terser reveal the names of the source files in the compressed output

Is there a way to stop source filenames from appearing in webpack output even when using Terser for minification? Illustration After minifying my production React app build, the resulting .js output file still contains original source filenames rather th ...

Discovering the process of mapping transitions in MUI

I'm struggling with mapping my products in mui and placing each one in Grow. However, I keep getting this error message: "Warning: Failed prop type: Invalid prop children of type array supplied to ForwardRef(Grow), expect a single ReactElement". Can a ...

Testing in Jasmine: Verifying if ngModelChange triggers the function or not

While running unit tests for my Angular app, I encountered an issue with spying on a function that is called upon ngModelChange. I am testing the logic inside this function but my test fails to spy on whether it has been called or not! component.spec.js ...

Using ReactJS to transform my unique array into an object before appending it to a list

Here is the array I am working with: [{…}] 0: {id: 2, createdAt: "2021-06-11T10:13:46.814Z", exchangedAt: "2021-06-11T08:04:11.415Z", imageUrl: "url", user: "user", …} 1: .... 2: .... 3: .... .... length: 5 __pro ...

AngularJS issue: Form submission does not trigger the controller function

I am currently learning AngularJS and I am experimenting with the sample code below to send my form data to the server. <!doctype html> <html lang=''> <head> <meta charset="utf-8"> <script src="../js/angular.min.v1 ...

Facing a challenge with displaying an angularjs template within a popover

I am having trouble displaying custom HTML content in a popover when clicking on my "View" link. Although other content is rendering correctly, such as one with an ng-repeat inside it, my custom directive does not seem to be processed and displayed properl ...

What is the method to retrieve the return value from this ajax request?

Here's a code snippet: var information = { ObtainInfo : function() { var url = 'http://www.bungie.net/api/reach/reachapijson.svc/game/info/'+storage.get('apikey'); $.ajax({ url: url, su ...

Learn the best way to populate Google Map popup windows with multiple values and include a button to pass unique ID values

I'm facing an issue with my code. When I click on a marker, it should display "Madivala, 12.914494, 77.560381,car,as12" along with a button to pass ID values. Can someone help me figure out how to move forward? http://jsfiddle.net/cLADs/123/ <ht ...