5

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.

2
  • 1
    the component is likely not rendered before that script is run - you'll want to use import { onMounted } from 'vue'; onMounted(() => { console.log(document.querySelector('.test')) } Commented Mar 7, 2022 at 9:56
  • That was it! Do you want to post an answer? Commented Mar 7, 2022 at 10:02

4 Answers 4

9

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>
Sign up to request clarification or add additional context in comments.

Comments

4

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

2 Comments

Using onMounted is correct; however, not using Vue's built-in ref will cause issues. The code snippet above does not allow for multiple instances of this component to exist on one rendered view and behave as expected.
@weo3dev - indeed you are right. My answer was addressing the question as posted. Not sure why it would've been accepted :p
1

You could also use ref for accessing to your div dom;

<div ref="test" class="test">
        
const test= ref();
    
onMounted(() => console.log(test.value));

No need to use document.querySelector since the dom object is just in your page.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.