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

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

我是 Vue 3 的初学者。在学习 Vue 3 时,我遇到了在 Vue 3 模板中处理 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>

以上代码打印错误如下:

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

我也尝试了以下方法,但它们不是解决方案。

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

有人能告诉我使用 Typescript 处理 Vue 3 模板中的 DOM 对象的正确方法吗?

谢谢。

因为mainContainer是一个ref,你需要先访问它的值:

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

按如下方式输入您的参考:

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

然后使用.value访问元素:

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