vue3 ts使用合集

274 阅读2分钟

1、defineProps

基本使用

 // 基本写法
    const props=defineProps({
      user:{
        type:String,
        required:true
      },
      count:{
         type:Number,
         require:false,
         default:'1
      }
    })
    console.log(props.user);
    console.log(props.count);

defineProps 通过泛型参数来定义 props 的类型:

const props = defineProps<{
  user: string,
  count?: Number
}>()

如果需要给 props 设置默认值,需要使用 withDefaults 函数:

 import {withDefaults} from 'vue'
    const defaultProp=withDefaults(defineProps<{
     user: string,
     count?: Number
    }>(),{
      user: 'tian
      count :1
    })

也可以使用 响应式语法糖 解构 + defineProps 简化写法:

import {withDefaults} from 'vue'
const {user,count=1}=defineProps<{user: string, count?: Number}>()

复杂的 prop 类型

interface Book { title: string author: string year: number }
const props=defineProps<{book:book}>()

2、defineEmits

基本用法

<script setup lang="ts">
const emit=defineEmits(['change','update'])
</script>

基于选项

 const emit = defineEmits({ 
     change: (id: number) => { 
         // 返回 `true` 或 `false` 
         // 表明验证通过或失败 
     }, 
     update: (value: string) => {
         // 返回 `true` 或 `false` 
         // 表明验证通过或失败 
     } 
 })

基于类型

const emit=defineEmits<{
  (e:'change',id:number):void,
  (e:'update',value:string):void
}>()

3.3+: 可选的、更简洁的语法

const emit=defineEmit<{
  change:[id:number],
  update:[value:string]
}>()

3、ref

根据初始化默认推导类型

import { ref } from 'vue'
// 推导出的类型:Ref<number> 
const year = ref(2024) 

设置类型

import {ref} from 'vue'
import type {Ref} fron 'vue'
const year:Ref<string|number>=ref('2024')
year.value = 2020
import {ref} from 'vue'
const year=ref<string|number>('2024')
year.value = 2020

如果你指定了一个泛型参数但没有给出初始值,那么最后得到的就将是一个包含 undefined 的联合类型:

// 推导得到的类型:Ref<number | undefined> 
const n = ref<number>()

4、reactive

ts自动推断参数类型

import { reactive } from 'vue'
// 推导得到的类型:{ name: string }
const student = reactive({ name: '张三' })

用接口标注类型

import {reactive} from 'vue'
interface user{
  name:string,
  age?:number
}
const student:user=reactive({name:'tian'})

5、computed

自动推导类型

import {ref,computed} from 'vue'
const count=ref(0)
// 推导得到的类型:ComputedRef<number> const double = computed(() => count.value * 2)
const double=computed(()=>count.value*2)

泛型显示指定类型

import {ref,computed} from 'vue'
const count=ref(0)
const double=computed<number>(()=>count.value*2)

6、事件处理函数标注类型

<script setup lang="ts">
    function handleChange(event:Event) { 
        console.log((event.target as HTMLInputElement).value)
    }
</script> 

<template>
    <input type="text" @change="handleChange" /> 
</template>

7. provide/indect 标注类型

impoer {provide,inject} from 'vue'
import type{InjectionKey} from 'vue'
const key=Symbol() as IndectionKey<string>

provide('key','foo')
// foo 的类型:string | undefined
const foo=inject(key)
// 类型:string | undefined
const foo=inject<sting>('foo')
// 传默认值,类型:string
const foo = inject<string>('foo', 'bar')

8、为模版应用注入类型

<script setup lang="ts">
    import { ref, onMounted } from 'vue'
    const el = ref<HTMLInputElement | null>(null) 
    // 3.5+
    //const el = useTemplateRef<HTMLInputElement>(null)
    
    onMounted(() => { el.value?.focus() }) 
</script> 
<template> 
    <input ref="el" /> 
</template>

9、为组件模板引用标注类型

<script setup lang="ts"> 
    import { useTemplateRef } from 'vue' 
    import Foo from './Foo.vue' 
    import Bar from './Bar.vue' 
    type FooType = InstanceType<typeof Foo> 
    type BarType = InstanceType<typeof Bar> 
    const compRef = useTemplateRef<FooType | BarType>('comp') 
</script>
<template>
    <component :is="Math.random() > 0.5 ? Foo : Bar" ref="comp" /> </template>

如果组件的具体类型无法获得,或者你并不关心组件的具体类型,那么可以使用 ComponentPublicInstance。这只会包含所有组件都共享的属性,比如 $el

import { useTemplateRef } from 'vue'
import type { ComponentPublicInstance } from 'vue'

const child = useTemplateRef<ComponentPublicInstance | null>(null)