简体   繁体   中英

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.

 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 . It's actually right there in the type for the ref: HTMLElement | null HTMLElement | null .

Change your onMounted callback to the following to check for that:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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