2

I am a beginner of Vue 3. While I'm studying Vue 3 I faced a problem for handling DOM in Vue 3 template. Here, the source code is.

MainContainer.vue

<template>
  <div class="main-container" ref="mainContainer">
    <button @click="randomBackgroundColor">Random Background Color</button>
  </div>
</template>

<script lang="ts">
import {defineComponent, ref, Ref} from 'vue';
export default defineComponent({
  setup() {
    const mainContainer = ref(null)

    const randomBackgroundColor = () => {
      mainContainer.style.backgroundColor = ["red", "green", "blue", "yellow", "black"][Math.floor(5 * Math.random())]
    }
    return { mainContainer, randomBackgroundColor }
  }
});
</script>

<style scoped>

</style>

The above code prints error as following:

ERROR in /webapp_vue/src/components/pc/MainContainer.vue.ts
8:20-25
[tsl] ERROR in /webapp_vue/src/components/pc/MainContainer.vue.ts(8,21)
      TS2339: Property 'style' does not exist on type 'Ref<null>'.

webpack 5.28.0 compiled with 1 error in 15963 ms

I also tried as followings but they were not the solution.

const mainContainer = ref(null) as Ref<HTMLElement | null>
// or
const mainContainer = ref<HTMLElement | null>(null)

Can someone tell me the correct way to handle DOM object in template of Vue 3 with Typescript?

Thank you.

2 Answers 2

2

Since mainContainer is a ref, you need to access its value first:

const randomBackgroundColor = () => {
    mainContainer.value.style.backgroundColor = ["red", "green", "blue", "yellow", "black"][Math.floor(5 * Math.random())]
}
Sign up to request clarification or add additional context in comments.

Comments

0

Type your ref as follows :

const mainContainer = ref<HTMLDivElement | null>(null)

then use .value to access the element :

   mainContainer.value.style.backgroundColor = ["red", "green", "blue", "yellow", "black"][Math.floor(5 * Math.random())]

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.