Skip to content

vue3 + TypeScript 使用指南

为 ref() 标注类型

  1. 使用泛型
ts
import { ref } from 'vue'

const initCode = ref<string | number>('200')
  1. 通过使用 Ref 这个类型为 ref 内的值指定一个更复杂的类型
ts
import { ref } from 'vue'
import type { Ref } from 'vue'

const initCode: Ref<string | number> = ref('200')

推荐
比较推荐使用第一种方式。因为第二种方式需要额外的引入 Ref,本着能少写一行是一行原则

为 reactive 标注类型

  1. 直接给声明的变量添加类型
js
import { reactive } from 'vue'

interface User {
  name: string
  age: string | number
}

const user:User = reactive({
  name:"前端开发爱好者",
  age:'20'
})
  1. 通过泛型参数的形式来给 reactive()增加类型
js
import { reactive } from 'vue'

interface User {
  name: string
  age: string | number
}

const user = reactive<User>({
  name:"前端开发爱好者",
  age:'20'
})

推荐
不推荐使用 reactive() 的泛型参数,因为处理了深层次 ref 解包的返回值与泛型参数的类型不同。推荐直接给声明的变量添加类型。

defineProps

在组合式 API 中,通过 defineProps 来定义 props

运行时声明

js
import { defineProps } from "vue"

const props = defineProps({
    name: {
        type: string,
        require: true
    }
})

props.name

基于类型的声明

js
const props = defineProps<{
    name: string
}>()

或把泛型参数定义成单独的 interface

js
interface Props {
    name: string
}

const props = defineProps<Props>()

支持默认值

  1. 支持默认值方法1
js
export default {
    plugins: [
        vue({
            reactivityTransform: true
        })
    ]
}

通过对 defineProps() 的响应性解构来添加默认值

js
interface Props {
  name: string
}

const { name = '前端开发爱好者' } = defineProps<Props>()
  1. 支持默认值方法2 通过使用 withDefaults
js
const props = withDefaults(defineProps<{
  name: string
}>(), {
  title: '测试标题'
})

defineEmits

在组合式 API 中,通过 defineEmits 来定义 emit

  1. 默认使用方式
js
const emit = defineEmits(['closeDialog'])
emit('closeDialog')
  1. 类型判断方式
js
const emit = defineEmits<{
  (e: 'setThemeColor', val: string): void
}>()

或者提取出来

js
interface Emit {
	(e: 'setThemeColor', value: string): void
}

const emit = defineEmits<Emit>()