简体   繁体   English

在 vue.js typescript 中键入 DOM ref

[英]Typing the DOM ref in the vue.js typescript

I'm just wondering why my ref to a simple button won't work in typescript.我只是想知道为什么我对一个简单按钮的ref在 typescript 中不起作用。 I created a simple button and a constant and then when component is mounted I check if the ref is null or not.我创建了一个简单的按钮和一个常量,然后在安装组件时检查 ref 是否为null otherwise make the button un-disabled...否则使按钮取消禁用...

Here is the example code:这是示例代码:

<template>
 <input v-model="phone" type="text" />
 <button ref="phoneSubmitBtn" type="button" disabled>تایید</button>
</template>

<script lang="ts" setup>
import { Ref, ref, watch, onMounted } from 'vue';

const phoneSubmitBtn: Ref<HTMLButtonElement>|Ref<null> = ref(null);
let phone: Ref<string> | Ref<null> = ref(null);

onMounted(() => {
    if (phoneSubmitBtn.value === null) { 
        return false
    }

    watch(phone, () => {
        if (phone.value !== null && phone.value.length === 11) {
            phoneSubmitBtn.value.disabled = false;
        } else{
            phoneSubmitBtn.value.disabled = true;
        }
    })
})
</script>

Note: Logic works fine and everything works as well but the VSCODE tells me that phoneSubmitBtn.value.disabled: Property 'value' does not exist on type 'never'.ts(2339) inside of the watch section.注意:逻辑工作正常,一切正常,但VSCODE告诉我phoneSubmitBtn.value.disabled: Property 'value' does not exist on type 'never'.ts(2339) inside the watch section。

phoneSubmitBtn is incorrectly typed, it's narrowed down to Ref<null> on assignment because it's a constant, so the type of phoneSubmitBtn.value is null . phoneSubmitBtn输入错误,因为它是一个常量,所以它在赋值时缩小到Ref<null> ,所以null phoneSubmitBtn.value

It should have been:它应该是:

const phoneSubmitBtn: Ref<HTMLButtonElement | null> = ref(null);

Since ref a generic, variable type can be inferred:由于ref是通用的,可以推断出变量类型:

const phoneSubmitBtn = ref<HTMLButtonElement | null>(null);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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