Vue中的TypeScript(二)使用的那些事

65 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第6天,点击查看活动详情

前言

假设你对Vue和TypeScript都有一定的了解了,想要开始大刀阔斧的重构你的项目或者重新开发一个新项目时,有一些事情我们还是注意到的,尽管看起来不是很重要,但却是很基础的。正所谓,不积跬步无以至千里,不积小流无以成江海就是这个道理。

那些事

  • defineComponent():你可能会在较多场景下看到过defineComponent()这个方法,他其实就是为了能够更准确的推导出组件选项内的类型。
import { defineComponent } from 'vue'

export default defineComponent({
  // 启用了类型推导
  props: {
    name: String,
    msg: { type: String, required: true }
  },
  data() {
    return {
      count: 1
    }
  },
  mounted() {
    this.name // 类型:string | undefined
    this.msg // 类型:string
    this.count // 类型:number
  }
})

当然,在组合式API中对于prop的传递内容也是支持推导的。

  • lang='ts':想要组件中的表达式变量都享受更好的类型检查时,还需要在<script>标签上加上 lang='ts'的属性。
<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  data() {
    return {
      num: 1
    }
  }
})
</script>

<template>
  <!-- 自动开启类型检查和自动补全 -->
  {{ num.toFixed(2) }}
</template>

当然,在<script setup>中lang='ts'也是同样适用的。

<script setup lang="ts">
// 启用了 TypeScript
import { ref } from 'vue'

const num = ref(1)
</script>

<template>
  <!-- 自动开启类型检查和自动补全 -->
  {{ num.toFixed(2) }}
</template>

当我们使用了lang='ts',在<template>中的表达式语法也是支持类型检查的。

<script setup lang="ts">
let num: string | number = 1
</script>

<template>
  <!-- 因为 x 可能是字符串,所以这么写是会报错的 -->
  {{ num.toFixed(2) }}
</template>

这个时候我们就可以通过类型断言的形式解决这个问题。

<script setup lang="ts">
let num: string | number = 1
</script>

<template>
  {{ (num as number).toFixed(2) }}
</template>

不过,最好是要在我们使用num变量之初就把,就把它的类型规定好,避免出现无法提示的问题。