返回列表 发帖

Vue 3.0 TypeScript支持#开发工具

#项目创建
Vue CLI 可以生成使用 TypeScript 的新项目,开始:

## 1. Install Vue CLI, 如果尚未安装
npm install --global @vue/cli@next
## 2. 创建一个新项目, 选择 "Manually select features" 选项
vue create my-project-name
## 3. 如果已经有一个不存在TypeScript的 Vue CLI项目,请添加适当的 Vue CLI插件:
vue add typescript
请确保组件的 script 部分已将语言设置为 TypeScript:

<script lang="ts">
  ...
</script>
#编辑器支持
对于使用 TypeScript 开发 Vue 应用程序,我们强烈建议使用 Visual Studio Code,它为 TypeScript 提供了很好的开箱即用支持。如果你使用的是单文件组件 (SFCs),那么可以使用很棒的 Vetur extension,它在 SFCs 中提供了 TypeScript 推理和许多其他优秀的特性。

WebStorm 还为 TypeScript 和 Vue 提供现成的支持。

#定义 Vue 组件
要让 TypeScript 正确推断 Vue 组件选项中的类型,需要使用 defineComponent 全局方法定义组件:

import { defineComponent } from 'vue'
const Component = defineComponent({
  // 已启用类型推断
})
#与 Options API 一起使用
TypeScript 应该能够在不显式定义类型的情况下推断大多数类型。例如,如果有一个具有数字 count property 的组件,如果试图对其调用特定于字符串的方法,则会出现错误:

const Component = defineComponent({
  data() {
    return {
      count: 0
    }
  },
  mounted() {
    const result = this.count.split('') // => Property 'split' does not exist on type 'number'
  }
})
如果你有一个复杂的类型或接口,你可以使用 type assertion 对其进行强制转换:

interface Book {
  title: string
  author: string
  year: number
}
const Component = defineComponent({
  data() {
    return {
      book: {
        title: 'Vue 3 Guide',
        author: 'Vue Team',
        year: 2020
      } as Book
    }
  }
})

返回列表