Vue Composition API-使用TypeScript获取引用

时间:2020-07-21 20:37:51

标签: typescript vue.js ref vue-composition-api

Vetur在下面的这一行上为空强调:

const firstRef = ref<HTMLElement>(null)
No overload matches this call.
 Overload 1 of 3, '(raw: HTMLElement): Ref', gave the following error.
  Argument of type 'null' is not assignable to parameter of type 'HTMLElement'.
 Overload 2 of 3, '(raw: HTMLElement): Ref', gave the following error.
  Argument of type 'null' is not assignable to parameter of type '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>

2 个答案:

答案 0 :(得分:4)

根据Vetur的回复,您不能将null类型转换为HTMLELement类型。解决此问题的一种可能方法是编写:

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

但是请记住,每次要使用firstRef时,都必须检查其类型是否为null。您也可以执行以下操作:

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

答案 1 :(得分:0)

另一种方法可能是可选链接(自TS 3.7起):

firstRef.value?.focus()

这对于TS来说很好,并且仅当firstRef.value不为null或未定义时才执行命令。