typescript - Vue Composition API - 使用 TypeScript 获取引用

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

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

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)

Here's a condensed context. Any ideas what I did wrong?

<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>

最佳答案

正如 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.
}

关于typescript - Vue Composition API - 使用 TypeScript 获取引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63022740/

相关文章:

javascript - 如何替换 REACT.js 中的 refs(antd 表示例)

c# - 可以安全地假设由 new 初始化的所有 C# 变量都是引用吗?

javascript - 如何为根组件 dom 元素添加样式( Angular 选择器组件)

Angular 6 : Reactive Form's updateOn: 'submit' is not updating value after submitting

javascript - TypeScript:描述对象的对象

css - 应用 Primevue 主题

javascript - 如何在 ES6 中的 Vue.js 中使用谷歌地图

javascript - Vue.js/webpack : how do I clear out old bundle main-*. js 文件,当热重载转译它们时?

typescript - 使用 Nest.js 在 AWS Lambda 中获取 Cognito 数据(即 requestContext)

c# - 如何使用 ref struct 参数和未知返回类型调用内部方法