Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
Access dom element list of classes with Vue 3 composition API

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"
          :class="{ chatUpdated: this.chatSessionId === tab.chatSessionId }"
        >
          {{ 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.

about 4 years ago ยท Juan Pablo Isaza
2 answers
Answer question

0

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
about 4 years ago ยท Juan Pablo Isaza Report

0

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:

            ๐Ÿ‘‡
onMounted(async () => {
    ๐Ÿ‘‡
  await nextTick()

  // class list effect is now available
  console.log(tabLink.value[0].classList[0])
})

demo

about 4 years ago ยท Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!