Search code examples
typescriptvue.jsdomvuejs3ref

How to handle DOM object in template of Vue 3 with Typescript


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.


Solution

  • 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())]