Home > Back-end >  How to target elements inside <script setup> of Vue 3 component?
How to target elements inside <script setup> of Vue 3 component?

Time:03-07

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

<template>
  <div id="test" >

  </div>
</template>


<script setup>

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

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

CodePudding user response:

the component is not rendered before that script is run

You want to wait until it is mounted

<template>
  <div id="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

CodePudding user response:

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>

CodePudding user response:

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

CodePudding user response:

You should be able to select your element by giving it a ref value

<div ref="test">

</div>

Then select it from within a method

test_element = this.$refs.test
  • Related