我是 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)
有人可以告诉我在 Vue 3 模板中使用 Typescript 处理 DOM 对象的正确方法吗?
谢谢。
最佳答案
由于 mainContainer
是一个引用,因此您需要首先访问它的值:
const randomBackgroundColor = () => {
mainContainer.value.style.backgroundColor = ["red", "green", "blue", "yellow", "black"][Math.floor(5 * Math.random())]
}
关于typescript - 如何使用 Typescript 处理 Vue 3 模板中的 DOM 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66817481/