As I delve into the world of Vue 3 as a beginner, I encountered a challenge when it came to managing the DOM within Vue 3 templates. Let's take a look at the source code.
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 snippet yields an error message:
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 attempted a couple of solutions, but unfortunately, they did not resolve the issue.
const mainContainer = ref(null) as Ref<HTMLElement | null>
// or
const mainContainer = ref<HTMLElement | null>(null)
If anyone can guide me on the appropriate way to handle DOM elements within the Vue 3 template using Typescript, I would greatly appreciate it.
Thank you.