最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to target elements inside <script setup> of Vue 3 component? - Stack Overflow

programmeradmin4浏览0评论

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.

Share Improve this question edited Sep 25, 2022 at 6:53 Boussadjra Brahim 1 asked Mar 7, 2022 at 9:51 Artur Müller RomanovArtur Müller Romanov 5,80119 gold badges109 silver badges190 bronze badges 2
  • 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
Add a ment  | 

4 Answers 4

Reset to default 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>

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

发布评论

评论列表(0)

  1. 暂无评论