Vue3中使用TypeScript给ref数据添加类型

2,761 阅读1分钟

最近用vue3和ts搭了个项目,通常都是使用return 一个 reactive({})去操控响应式数据,最近用起了ref(),在vue3中 想给ts的值添加类型,但是取值又是.value,开始也摸索了一会儿

const userInfoList = ref('')

定义一个用户信息列表

这时候我们拿到的值是userInfoList.value,直接给类型肯定会报错

先定义一个我们想要的类型Interface

interface User {
  age: number
  gender: string
  headimg: any
  id: number
  mail: string
  nickname: string
  openid: any
  password: string
  phone: string | number
  recordtime: string
  state: string
  username: string
}

正确的负值

const userInfoList: Ref<User | null> = ref(null)

我们需要给我们的值一个null类型,并初始给null。