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?