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

Troubleshooting Compatibility Issues: JavaScript Function Works in Chrome but not in Internet

After collaborating with fellow coders to develop info boxes using HTML, CSS, and JavaScript, I have come across an issue with the hover functionality not working properly in Internet Explorer. Interestingly, everything functions flawlessly on Google Chrom ...

AngularJS directive for attributes. Steps for adding a second attribute directive during compilation phase

I am interested in creating an attribute directive that adds an icon to a button when it is disabled. Click here to see a similar example on Fiddle In addition, I would like to include the ng-disabled directive during the compile process (with the value ...

Exploring the Potential of Mobile Development using AngularJS

I am in the process of creating an app with the following key design objectives: Efficiency and modularity - a light core that can be expanded to create a feature-rich app in a cohesive manner Mobile focus - this app is primarily aimed at mobile platform ...

Is there a way to alter the data type of a JavaScript object?

Currently, I'm developing a browser-based text adventure game that takes inspiration from classics like Hitchhiker's Guide to the Galaxy and the Zork series. In order to allow players to save their progress, I store important objects such as loca ...

Function fails to execute after drop-down menu selection

I set up a double drop-down feature and implemented my function calling code. However, after choosing an option from the drop-down menus, the function is not getting executed. The purpose of the code is to trigger a specific function based on the selectio ...

verify selection on php page using javascript

I'm having trouble with confirming the deletion of something. Despite getting an alert message when clicking the 'deleteReply' button, nothing else appears to be happening. I've tried echoing the posted variable but it's not workin ...

Writing a CSV file to AWS S3 proves to be unsuccessful

I have been working with TypeScript code that successfully writes a CSV file to AWS S3 when running locally. However, I have recently encountered an error message: s3 upload error unsupported body payload object NOTES: The code is not passing creden ...

Parameterized Azure Cosmos DB Stored Procedure

I am currently learning about Azure Cosmos Db, and I am in the process of developing a simple JavaScript stored procedure that will return a document if a specific Id is provided. However, when I run the stored procedure, I do not receive a "no docs foun ...

Bring in all subdirectories dynamically and export them

Here is what I currently have: -main.js -routeDir -subfolder1 -index.js -subfolder2 -index.js ... -subfolderN -index.js Depending on a certain condition, the number of subfolders can vary. Is there a way to dynam ...

Gathering information from mapped objects when they are clicked in a React application

Do you know how to retrieve genre.id when a user clicks on a Button and triggers the onClick function? Your assistance is greatly appreciated. ... return ( <div className="App"> <Header /> <div className="A ...

Issue with improper lighting on Three.Geometry objects when using LambertMaterial in Three.js

After enhancing my initial version of this inquiry (previously asked question) with a JSFiddle showcasing the latest build of Three.JS and illustrating the lighting issue on Three.Geometry, I encountered difficulties with dependencies in Stack Snippets. Ho ...

Altering the backdrop upon hovering over an element

As a beginner in Javascript and Jquery, I am working on creating an interactive feature where hovering over one element changes the background image in another column. I have managed to write the function, but now I want to add an animation to the image tr ...

The specified type '{ state: any; dispatch: React.Dispatch<{ type: string; value: any; }>; }' is not compatible with the expected type

I've been working on a UI layout that includes checkboxes on the left, a data table on the right, and a drop zone box. The aim is to keep the table data updated whenever a new file is dropped, and also filter the data based on checkbox selection. I ma ...

Accessing a specific attribute of an object contained within an array

Currently, I am utilizing Vue.js in my project and have implemented a method that involves comparing values from two different arrays. array1: [{ name: 'test1', somevar: true }, { name: 'test2', somevar: false }] array2: ['test1 ...

How to Resubmit a Form Using Ajax?

My form utilizes ajax to call the server for user authentication. However, I've encountered an issue where if a user enters the wrong password and then tries to correct it, any subsequent calls do not trigger the on('submit') function, leavi ...

Creating a new Express JS application

I've encountered an issue with my express application. When I run the server and navigate to localhost in my browser, the index page loads but without the image that should be displayed. The browser console shows a 404 error for the image URL. GET ht ...

When I select an option with an object, ng-model is receiving '[object Object]' instead of the actual object for <select> element

Referencing an example from Angular documentation: this link, specifically the section on "Using ngValue to bind the model to an array of objects." In the index.html file: <!doctype html> <html lang="en"> <head> <meta charset="UTF- ...

When coding in JavaScript, the value of "this" becomes undefined within a class function

I'm facing an issue with my TypeScript class that contains all my Express page functions. When I try to access the class member variable using this, I get an 'undefined' error: class CPages { private Version: string; constructor(ver ...

In Vue3, a certain variable can be set either through props or using ref

// Here is some pseudo code for handling modelValue and image props = { modelValue? } image = ref() onPageLoad = function { if modelValue is null then: image.value = await api.get() } <button @onClick> // Displaying image based on condition ...

Issue with Nuxt: Data inaccessible within a method

Incorporating CKEditor 5 + CKFinder (Modal Mode) to initiate image selection through the @click event presents a challenge in accessing data within the onInit function block. Below is the function in question: data() { return { post: { ...