I'm trying to watch if a class exist in a dom element inside my component but can't figure out the way to do this inside the onMounted hook:
This a simplified version of my template:
<template>
<a
ref="tabLink"
href="#"
role="tab"
:
>
{{ tab.title }}
</a>
</template>
This is my setup function:
setup() {
const tabLink = ref(null);
onMounted(() => {
console.log(tabLink.value["0"].classList[0]);
});
}
As you can see I'm trying to console.log the classes of my <a>
tag in my template but I always get an undefined value. I thought that the component's DOM was already there when the onMounted hook is called so I don't get why I'm getting an undefined value.
CodePudding user response:
The way you look for the class is wrong.
You need to:
const tabLink = ref(); // remove the null from here
console.log(tabLink.value.className); // gets all the classes as string
console.log(tabLink.value.className.split(" ")); // returns an array of classes
CodePudding user response:
From the Vue docs:
When you mutate reactive state in Vue, the resulting DOM updates are not applied synchronously. Instead, Vue buffers them until the "next tick" to ensure that each component updates only once no matter how many state changes you have made.
In your case, there's a class binding on the <a>
which changes based on chatSessionId
. That binding's effect is seen in the next tick.
Solution
Await a call to nextTick()
to observe the effect: