vue3中怎么使用typescript

114 阅读1分钟

1. ref 和 reactive

// 先定义接口
interface good {
    id: string
    name: string
    price: number
}
// reactive写法
const goods = reactive<good[]>([{
      id: '1001',
      name: '男士鞋子',
      price: 280
    },{
      id: '1002',
      name: '男士卫衣',
      price: 180
}])
// ref写法
let goods1 = ref<good[]>([])
    goods1.value = [{
      id: '1001',
      name: '男士鞋子',
      price: 280
    },{
      id: '1002',
      name: '男士卫衣',
      price: 180
}]

2. defineProps

// 父组件
    const money = ref<number>(10)
    const halfMoney = computed(() => {
      return money.value / 2
    })
    
    const msg:string = 'nihao'
    const age:number = 10
    
<template>
    <div>
        <p v-for="item in goods" :key="item.id">
          {{item.name}}现在仅需{{item.price}}元,
        </p>
        {{ halfMoney }}
        <HelloWorld :msg="msg" :age="age"></HelloWorld>
    </div>
</template>

// 子组件
defineProps<{
  msg: string
  age: number
}>()

3. defineEmits

// 子组件
const money = ref<number>(50)
const message = ref<string>('wobuhao')

const emit = defineEmits<{
  (e: 'changeMoney', money: number): void
  (e: 'changeMsg', message: string): void
}>()

emit('changeMoney', money.value)
emit('changeMsg', message.value)

// 父组件
//template标签中
<HelloWorld @changeMoney="hchangeMoney" :msg="msg" :age="age"></HelloWorld>

//script标签中
const hchangeMoney:(e: number) => void = (e) => {
      console.log(e);
} 

4. 获取事件对象的数据类型

通过打印事件对象来查看该对象的类型

5. 获取原生DOM,以及原生DOM的数据类型

通过 document.createElement 这个api来看返回值得知特殊HtmlElement的类型

6.获取组件的引用,以及该引用的数据类型

const MyComRef = ref<InstanceType<typeof MyCom> | null>(null)