Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

238
Visualizações
How to target elements inside <script setup> of Vue 3 component?

How can I target the element with test class inside this vue component:

<template>
  <div id="test" class="test">

  </div>
</template>


<script setup>

console.log(document.querySelector('.test'))
</script>

This component is imported into another component. The console outputs null.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

the component is not rendered before that script is run

You want to wait until it is mounted

<template>
  <div id="test" class="test">

  </div>
</template>


<script setup>

import { onMounted } from 'vue'; 
onMounted(() => { 
    console.log(document.querySelector('.test')) 
});
</script>

In general, there's hardly ever any need to use DOM methods like that in vue though - I won't say never, because I know as soon as I say that, someone will come up with a valid reason to

I never have though

about 4 years ago · Juan Pablo Isaza Relatório

0

The best practice is to use ref instead of DOM manipulations methods, and also use onMounted hook to check the element as mentioned in the following example:

<script setup>
import { ref,onMounted } from 'vue'

const input =ref()
onMounted(()=>{

  input.value.focus()
})
</script>

<template>

  <input  ref="input">
</template>
about 4 years ago · Juan Pablo Isaza Relatório

0

you can use onMounted for target the element inside vue component:

<script setup>
import { onMounted } from 'vue'

onMounted(() => {
  console.log(document.querySelector('.test'));
})
</script>

but I recommend use ref instead of DOM manipulations method:

<script setup>
import { ref, onMounted } from 'vue'

const el = ref()

onMounted(() => {
  el.value // <div>
})
</script>

<template>
  <div ref="el"></div>
</template>

docs: https://vuejs.org/api/composition-api-lifecycle.html#onmounted

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda