Vue Composition API - 使用 TypeScript 获取引用

nst*_*ant 7 ref typescript vue.js vue-composition-api

Vetur 在下面这一行下划线 null:

const firstRef = ref<HTMLElement>(null)
Run Code Online (Sandbox Code Playgroud)
没有重载匹配这个调用。
 Overload 1 of 3, '(raw: HTMLElement): Ref', 给出了以下错误。
  “null”类型的参数不能分配给“HTMLElement”类型的参数。
 重载 2 of 3, '(raw: HTMLElement): Ref',出现以下错误。
  “null”类型的参数不能分配给“HTMLElement”类型的参数。Vetur(2769)

这是一个浓缩的上下文。任何想法我做错了什么?

<template>
  <input id="first" ref="firstRef">
  <button type="button" @click.prevent="focusFirst">Focus</button>
</template>

<script lang="ts">
import { defineComponent, ref } from "@vue/composition-api"
export default defineComponent({
  name: "Test",
  setup() {
    const firstRef = ref<HTMLElement>(null)
    const focusFirst = () => {
      const theField = firstRef.value
      theField.focus()
    }

    return { focusFirst }
  }
</script>
Run Code Online (Sandbox Code Playgroud)

Kei*_*eno 8

As given back by Vetur, you cannot convert a null type to an HTMLELement type. A possible way to fix this would be to write:

const firstRef = ref<HTMLElement | null>(null)
Run Code Online (Sandbox Code Playgroud)

However, keep in mind that you'll have to check if firstRef is of type null every time you want to use it. You could do something like this as well:

if (firstRef.value) {
  // do stuff with firstRef
  // typescript knows that it must be of type HTMLElement here.
}
Run Code Online (Sandbox Code Playgroud)

  • 我才刚刚开始,所以我不确定优点/缺点,但似乎你可以使用 `const firstRef = ref&lt;HTMLElement&gt;()`,这只会使 ref `HTMLElement | undefined`,但它有点短。从技术上讲,您还可以使用“ref&lt;HTMLElement&gt;(null!)”之类的内容覆盖类型系统,但这可能是一个坏主意,因为它可能会导致在初始化 ref 之前(例如在安装组件之前)使用不安全的情况。 (4认同)