I am using a v-for statement 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 created a variable people which held all created elements. When used in one function it worked, in another, it didn't.
On further inspection, it is empty in the second function. I would create one variable to be used by both, but the variable can't be created until the page renders (I tried lifecycle hooks, they didn't work either).
filterByName () { // this method worked
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 didn't enter any for loops
const people = document.querySelectorAll(".person")
console.log(people.length) // this returned 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 real question is: Why does one work but not the other, how do I get them both to work?
I think you need to provide more information about how you call these two functions. In theory, they can work only in mounted hook, please check this.
Btw, since you created these elements by users, why don't you just use this.users instead of const people and use v-show to control display style? If this.users is not in the component you are working on, you can consider about using props or Provide/Inject or pinia/vuex. Operating document directly may not be a good choice.