请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

关于vue中ref的类型声明

老师,我观察到element-plus的源码中,他会这样声明变量
比如 const name = ref(null)
按理说null是无法转换成string的呀,请问老师他是做了什么配置吗

正在回答

4回答

1.

const name = ref(null) 这里写的 是 js 版本,转换为TS版本  const name:Ref = ref(null) 

Ref 默认泛型为any 可以接受任意数据类型的值

interface Ref<T=any>{

   value:T

}  


2.使用场景还用:当我们在运行后才确定 ref.value的值,就可以这样使用

例如:获取组件上的Dom元素


//  通过ref来获取真实的DOM元素节点【查询顾客中的表单】,ref不带参数或null

let custListRef: Ref = ref(null) 或

let custListRef: Ref = ref() 或

let custListRef: Ref = ref(undefined) 或

custListRef.value.model;


提交答案系统出现了滞后,发重了一次,忽略


0 回复 有任何疑惑可以回复我~
  • 老师,element-plus就是ts写的
    他是这样 const name = ref<string>(null),感觉这样肯定会报错啊,但是他那儿就没事儿
    回复 有任何疑惑可以回复我~ 2021-11-17 14:52:59
  • 唯一原因就是 它的对应的tsconfig.json文件 配置的缘故:
    关闭了"strict": true   和  "strictNullChecks": true    ,下面的都能编译通过!
    let str: string = null
    let str2: number = null;
    let str3: boolean = null;
    let str4: object = null;
    let str5: unknown = null;
    let str6: any = null;
    let str7: void = null;
    回复 有任何疑惑可以回复我~ 2021-11-17 16:05:50
  • 非常感谢!
    回复 有任何疑惑可以回复我~ 2021-11-17 16:09:15
keviny79 2021-11-17 16:07:55


唯一原因就是 它的对应的tsconfig.json文件 配置的缘故:

关闭了"strict": true   和  "strictNullChecks": true    ,下面的都能编译通过!

https://img1.sycdn.imooc.com//szimg/6194b8270888e39110620686.jpg

0 回复 有任何疑惑可以回复我~
keviny79 2021-11-17 14:47:58

1.

const name = ref(null) 这里写的 是 js 版本,转换为TS版本  const name:Ref = ref(null) 

Ref 默认泛型为any 可以接受任意数据类型的值

interface Ref<T=any>{

   value:T

}  


2.使用场景:当我们在运行后由系统确定 ref.value的值时,就可以这样使用

例如:获取组件上的Dom元素


//  通过ref来获取真实的DOM元素节点【查询顾客中的表单】,ref不带参数或null

let custListRef: Ref = ref(null) 或

let custListRef: Ref = ref() 或

let custListRef: Ref = ref(undefined) 

custListRef.value.model;// 调用model数据




0 回复 有任何疑惑可以回复我~
keviny79 2021-11-17 14:47:51

1.

const name = ref(null) 这里写的 是 js 版本,转换为TS版本  const name:Ref = ref(null) 

Ref 默认泛型为any 可以接受任意数据类型的值

interface Ref<T=any>{

   value:T

}  


2.使用场景:当我们在运行后才确定 ref.value的值,就可以这样使用

例如:获取组件上的Dom元素


//  通过ref来获取真实的DOM元素节点【查询顾客中的表单】,ref不带参数或null

let custListRef: Ref = ref(null) 或

let custListRef: Ref = ref() 或

let custListRef: Ref = ref(undefined) 或

custListRef.value.model;




0 回复 有任何疑惑可以回复我~

相似问题

登录后可查看更多问答,登录/注册

问题已解决,确定采纳
还有疑问,暂不采纳
意见反馈 帮助中心 APP下载
官方微信