4. Vue3中使用TypeScript

直接参考Vue官方文档。

https://cn.vuejs.org/guide/typescript/overview.html#overview

一、TS与组合式API

1.为组件的 props 标注类型
2.为组件的 emits 标注类型
3.为 ref() 标注类型
4.为 reactive() 标注类型
5.为 computed() 标注类型
6.为事件处理函数标注类型
7.为 provide / inject 标注类型
8.为模板引用标注类型
9.为组件模板引用标注类型

二、TS与选项式AIP

1.为组件的 props 标注类型

(1)选项式 API 中对 props 的类型推导需要用 \color{red}{defineComponent()} 来包装组件。有了它,Vue 才可以通过 props 以及一些额外的选项,比如 required: true 和 default 来推导出 props 的类型:
\color{red}{(这和没学TS之前的写法是一样的)}

import { defineComponent } from 'vue'

export default defineComponent({
  // 启用了类型推导
  props: {
    name: String,
    id: [Number, String],
    msg: { type: Array, required: true, default: ()=>[] },
  },
  setup(props, { slots, attrs, expose, emit }) {}
}

(2)使用 \color{red}{PropType} 这个工具类型来标记更复杂的 props 类型,如 多层级对象函数签名

import { defineComponent } from 'vue'
import type { PropType } from 'vue'

interface Book {
  title: string
  author: string
  year: number
}

export default defineComponent({
  props: {
    book: {
      // 提供相对 `Object` 更确定的类型
      type: Object as PropType<Book>,
      required: true
    },
    // 也可以标记函数
    callback: Function as PropType<(id: number) => void>
  },
  setup(props, { slots, attrs, expose, emit }) {}
})
2.为组件的 emits 标注类型
3.为计算属性标记类型
4.为事件处理函数标注类型
5.扩展全局属性
6.扩展自定义选项
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容