gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 06:36:57 29 4
gpt4 key购买 nike

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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com