How can I target the element with test
class inside this vue ponent:
<template>
<div id="test" class="test">
</div>
</template>
<script setup>
console.log(document.querySelector('.test'))
</script>
This ponent is imported into another ponent. The console outputs null
.
How can I target the element with test
class inside this vue ponent:
<template>
<div id="test" class="test">
</div>
</template>
<script setup>
console.log(document.querySelector('.test'))
</script>
This ponent is imported into another ponent. The console outputs null
.
-
1
the ponent is likely not rendered before that script is run - you'll want to use
import { onMounted } from 'vue'; onMounted(() => { console.log(document.querySelector('.test')) }
– Bravo Commented Mar 7, 2022 at 9:56 - That was it! Do you want to post an answer? – Artur Müller Romanov Commented Mar 7, 2022 at 10:02
4 Answers
Reset to default 9The 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>
the ponent 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 e up with a valid reason to
I never have though
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.
you can use onMounted
for target the element inside vue ponent:
<script setup>
import { onMounted } from 'vue'
onMounted(() => {
console.log(document.querySelector('.test'));
})
</script>
but I remend 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/api/position-api-lifecycle.html#onmounted