Search code examples
javascriptvue.jsvuejs3vue-composition-apivue-script-setup

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.


Solution

  • 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