如何用Typescript处理Vue 3模板中的DOM对象

如何用Typescript处理Vue 3模板中的DOM对象,typescript,vue.js,dom,vuejs3,ref,Typescript,Vue.js,Dom,Vuejs3,Ref,我是VUE3的初学者。在学习VUE3的过程中,我遇到了一个在VUE3模板中处理DOM的问题。在这里,源代码是 MainContainer.vue <template> <div class="main-container" ref="mainContainer"> <button @click="randomBackgroundColor">Random Background Color&

我是VUE3的初学者。在学习VUE3的过程中,我遇到了一个在VUE3模板中处理DOM的问题。在这里,源代码是

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>

随机背景色
从“vue”导入{defineComponent,ref,ref};
导出默认定义组件({
设置(){
常量mainContainer=ref(空)
const randomBackgroundColor=()=>{
mainContainer.style.backgroundColor=[“红色”、“绿色”、“蓝色”、“黄色”、“黑色”][Math.floor(5*Math.random())]
}
返回{mainContainer,randomBackgroundColor}
}
});
上述代码打印错误,如下所示:

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

/webapp_vue/src/components/pc/MainContainer.vue.ts中的
错误
8:20-25
/webapp_vue/src/components/pc/MainContainer.vue.ts中的[tsl]错误(8,21)
TS2339:类型“Ref”上不存在属性“style”。
网页包5.28.0在15963毫秒内编译时出现1个错误
我也尝试了以下方法,但它们不是解决方案

const mainContainer = ref(null) as Ref<HTMLElement | null>
// or
const mainContainer = ref<HTMLElement | null>(null)
const mainContainer=ref(null)作为ref
//或
常量mainContainer=ref(空)
有人能告诉我用Typescript在Vue 3的模板中处理DOM对象的正确方法吗


谢谢。

由于
maincainer
是一个ref,您需要首先访问它的值:

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

按如下方式键入您的ref:

const mainContainer = ref<HTMLDivElement | null>(null)
   mainContainer.value.style.backgroundColor = ["red", "green", "blue", "yellow", "black"][Math.floor(5 * Math.random())]