简体   繁体   English

Vue typeScript“可能是 null object 错误”en ref.value

[英]Vue typeScript "possibly null object error" en ref.value

I target a with a ref="header" I'm trying to change css rules but a typeScript error is not letting me.我以 ref="header" 为目标 我正在尝试更改 css 规则,但 typeScript 错误不允许我这样做。

 const header = ref<HTMLElement | null>(null)

    onMounted(() => {
      header.value.style.color = "red"
    })

在此处输入图像描述

The error is perfectly reasonable: you can't be sure that that element exists.该错误是完全合理的:您无法确定该元素是否存在。 And if the element doesn't exist, you template ref's value will be null .如果该元素不存在,则模板引用的值将为null It's actually right there in the type for the ref: HTMLElement | null它实际上就在 ref 的类型中: HTMLElement | null HTMLElement | null . HTMLElement | null

Change your onMounted callback to the following to check for that:将您的onMounted回调更改为以下内容以检查:

onMounted(() => {
  if (header.value)
    header.value.style.color = "red"
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM