vue3+ts中定義ref變量,設置變量類型方式
更新時間:2024年03月15日 09:10:33 作者:chendf_
這篇文章主要介紹了vue3+ts中定義ref變量,設置變量類型方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
vue3+ts定義ref變量,設置變量類型
給定義的 ref 的值設置類型
<template> <el-input ref="input"></el-input> </template> //.... import {Ref, ref} from 'vue' const input: Ref<HTMLElement> = ref(null)
這樣寫之后會導致編譯報錯(vuetur報錯)
Type 'Ref<null>' is not assignable to type 'Ref<HTMLElement>'.
Type 'null' is not assignable to type 'HTMLElement'.Vetur(2322)
解決辦法
增加null類型
const input: Ref<HTMLElement | null> = ref(null)
在聲明文件(*.d.ts)中定義一個類型聲明
// 定義聲明 declare type Nullable<T> = T | null // 使用的地方只需要 const input: Ref<Nullable<HTMLElement>> = ref(null)
vue3 ts語法定義ref對象
分為兩步:
1.引入Ref 的 type
import type { Ref } from 'vue';
2.定義Ref類型的對象
let tableData:Ref = ref({});
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
vue中radio根據動態(tài)值綁定checked無效的解決
這篇文章主要介紹了vue中radio根據動態(tài)值綁定checked無效的解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03