TypeScript在vue3中的应用(Ref和ComputedRef的应用)

首先,我承认,我vue3和ts都不是很熟。然后在使用过程中就发现了这样一个情况。

复制代码
const list: {isBoob: boolean; count: number;}[] = computed(() => {
  let arr: number[] = new Array(total.value).fill(0).fill(1, 0, boobNumber.value) // 初始化数组
  arr = arr.sort((a,b) => Math.random() - 0.5) // 随机排序
  return arr.map((item: number, index): {isBoob: boolean; count: number;} => {
    // 返回对象组成的数组
    return {
      isBoob: !item,
      count: index
    }
  })
})
// error:类型"ComputedRef<{ isBoob: boolean; count: number; }[]>"缺少类型"{ isBoob: boolean; count: number; }[]"的以下属性: length, pop, push, concat 及其他 29 项。

其实现在想来,提示也很明白了,list的类型是ComputedRef<{ isBoob: boolean; count: number; }[]>,但是我当时没搞懂ComputedRef是什么,所以懵住了。

这里介绍vue3的特点,vue3在定义响应式数据时,需要使用x = ref()包裹数据,计算数据需要x = computed()。使用的时候也需要用 x.value。

所以对于变量x来说,他的数据类型一定不是括号内的内容或者说value的类型。

而ts为了应对这种情况就有了Ref和ComputedRef,分别表示这两种响应式数据。

复制代码
x :Ref<number> = ref(10)

x :ComputedRef<number> = computed(() => x*2)
相关推荐
用户15815963743704 分钟前
AI Agent 说"完成了",但其实没有——任务验收机制的工程实践
javascript
Carsene9 分钟前
开源项目文档架构设计:Git Submodule 实现文档与代码的优雅分离
前端·后端
Z思学13 分钟前
promise 有几种状态 async/await 和promise 有什么关系
前端
han_14 分钟前
JavaScript设计模式(四):发布-订阅模式实现与应用
前端·javascript·设计模式
276695829217 分钟前
租车帮(悟空)订单查询算法分析
java·服务器·前端·悟空·悟空app·租车帮·租车帮逆向
用户3266584037427 分钟前
如何初始化 TypeScript + Node.js 项目
javascript
__雨夜星辰__28 分钟前
TypeScript 入门学习笔记(面向对象 + 常用设计模式)
前端·学习·typescript
晚霞的不甘44 分钟前
HarmonyOS ArkTS 进阶实战:深入理解边距、边框与嵌套布局
前端·计算机视觉·华为·智能手机·harmonyos
_野猪佩奇_牛马版44 分钟前
ReACT Agent 开发知识点总结
前端
牛奶1 小时前
你发送的消息,微信到底怎么送到的?
前端·websocket·http