Home > Software engineering >  Why my element selector doesn't work after using <script setup> in vue.js?
Why my element selector doesn't work after using <script setup> in vue.js?

Time:11-19

Let say I want to change color of my element. Unfortunately, after use query Selector method, my code doesn't work but blank. Please anyone can solve this?

I try to select my element to change its color using javascript instead of using css

<template>
  <br><br><br>
<h1>Dashboard Page Here</h1>
</template>

<script>
export default {
  name: "xxxView",
}
</script>

<script setup>
const color = document.querySelector('h1');
color.style.color = 'green';
</script>

<style scoped>

</style>

CodePudding user response:

setup method is executed before the component elements are mounted to the DOM, you need to execute the DOM operations in the onMounted lifecycle

For example

<template>
  <br><br><br>
<h1>Dashboard Page Here</h1>
</template>

<script>
export default {
  name: "xxxView",
}
</script>

<script setup>
import { onMounted } from 'vue'
onMounted(() => {
  const color = document.querySelector('h1');
  color.style.color = 'green';
})
</script>

<style scoped>

</style>

But I suggest you if possible to use style directive instead.

CodePudding user response:

One method to access your "DOM" elements in Vue components is using "ref" as the code below:

<template>
  <br><br><br>
  <h1 ref="myHeader">Dashboard Page Here</h1>
</template>


<script setup>
import {ref, onMounted} from "vue";
const myHeader = ref(null)

onMounted(() => {
  myHeader.value.style.color = 'green';
})
</script>

<style scoped>

</style>

You can learn more about that in Vue.js docs

  • Related