将TypeScript与Vue单个文件组件一起使用

本文介绍了如何在Vue.js项目中开始使用TypeScript,包括使用Vue CLI 3生成已配置的TypeScript项目,配置TypeScript编译器,以及在单文件Vue组件中使用自定义数据类型。文章强调了TypeScript在Vue.js 3.0中的重要性,并提供了创建自定义接口和声明文件的基础知识。
摘要由CSDN通过智能技术生成

You might be asking yourself, “What is TypeScript”? Well, it’s one of the fastest growing programming languages that’s what! It’s a JavaScript superset created by Microsoft and turns the loosely typed language into strictly typed one; basically, it’s ES6 with optional type declarations. If you’re unsure where to start with TypeScript, I encourage you to read more about it.

您可能会问自己“什么是TypeScript”? 嗯,这是发展最快的编程语言之一! 它是Microsoft创建JavaScript超集,可将松散类型的语言转换为严格类型的语言。 基本上,它是带有可选类型声明的ES6。 如果您不确定从哪里开始使用TypeScript,建议您阅读更多有关它的内容

With that said, it’s never been a better time to start using TypeScript in your Vue.js projects. Evan You stated that, Vue.js 3.0’s code base will be rewritten entirely in TypeScript. This won’t affect ES6 developers, but it will by far improve the TypeScript experience.

话虽如此,现在在您的Vue.js项目中开始使用TypeScript从来没有比现在更好。 Evan You说过, Vue.js 3.0的代码库将完全用TypeScript重写。 这不会影响ES6开发人员,但到目前为止将改善TypeScript体验。

生成一个CLI项目 (Generate a CLI Project)

With Vue CLI 3, you can generate a new project with TypeScript already configured; just select “TypeScript” in the CLI prompt. While bootstrapping a new project, you’ll notice to that you can opt to use the “class-style component syntax”. If you are new to TypeScript, I recommend to not use the class-style syntax. Back in February, Evan You abandoned the class style syntax for the Vue 3.0 core library altogether. It’s a popular choice, but for those reasons, we will be going over how to use TypeScript with Vue.js without it.

使用Vue CLI 3,您可以生成一个已经配置了TypeScript的新项目。 只需在CLI提示符下选择“ TypeScript”。 在引导新项目时,您会注意到可以选择使用“类样式的组件语法”。 如果您不熟悉TypeScript,建议您不要使用类样式的语法。 早在二月份, Evan You就完全放弃了Vue 3.0核心库的类样式语法 。 这是一个流行的选择,但是由于这些原因,我们将讨论如何在不使用TypeScript和Vue.js的情况下使用它。

# Generate Vue project in current directory
$ vue create .

If you already have a Vue project created and want to add TypeScript support to it; you can do so with the following:

如果您已经创建了一个Vue项目,并想为其添加TypeScript支持,请执行以下操作: 您可以执行以下操作:

$ vue add typescript

配置TypeScript编译器 (Configuring the TypeScript Compiler)

Since TypeScript requires a build step, you can configure TypeScript to the needs of your team or project. There are a slew of options that you can enable or disable with the use of a tsconfig.json file. This file should live in the root directory of your project.

由于TypeScript需要构建步骤,因此您可以根据团队或项目的需要配置TypeScript。 您可以使用tsconfig.json文件启用或禁用大量选项 。 该文件应位于项目的根目录中。

Feel free to experiment with these options to find which is most useful for you and your project. I would recommend enabling noImplicitAny, noImplicitThis, noImplicitReturns at a minimum.

随意尝试这些选项,以找出对您和您的项目最有用的选项。 我建议至少启用noImplicitAnynoImplicitThisnoImplicitReturns

  • noImplicitAny: Raise error on expressions and declarations with an implied any type. This will throw an error if an argument, const, let, or var doesn’t have a type. This is more of a mental check on yourself to create custom data types for your code.

    noImplicitAny :在隐含any类型的表达式和声明上引发错误。 如果参数constletvar没有类型,则将引发错误。 这更像是对自己的心理检查,以便为代码创建自定义数据类型。

  • noImplicitThis: Similar to noImplicitAny but will throw an error with the this keyword. Another mental check to encourage you to type everything you can.

    noImplicitThis :类似于noImplicitAny但是this关键字将引发错误。 另一个精神检查,鼓励您键入所有可能的内容。

  • noImplicitReturns: Report an error when not all code paths in function return a value. This helps ensure that all conditions in a given function with a return type, returns a value.

    noImplicitReturns :当并非函数中的所有代码路径都返回值时,报告错误。 这有助于确保给定函数中带有返回类型的所有条件都返回一个值。

tsconfig.json
tsconfig.json
{
  "compilerOptions": {
    "module": "ES6",
    "noImplicitAny": true,
    "noImplicitThis": true,
    "noImplicitReturns": true,
    "sourceMap": true
  },
  "paths": {
    "@/*": [
      "src/*"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.vue"
  ],
  "files": [
    "src/vue-shims.d.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

基本和自定义数据类型 (Basic and Custom Data Types)

In TypeScript there 12 different types out of the box:

在TypeScript中,有12种不同的开箱即用类型:

  • boolean

    boolean

  • number

    number

  • string

    string

  • array

    array

  • object

    object

  • tuple

    tuple

  • enum

    enum

  • any

    any

  • void

    void

  • undefined

    undefined

  • null

    null

  • never

    never

The more common types that you will be using are the primitive types: string, number, boolean, null, undefined, and void. However, there will be times when you will need to create a custom data type. For that time, you can create something that TypeScript calls an Interface.

您将使用的更常见的类型是原始类型: stringnumberbooleannullundefinedvoid 。 然而, 会有时候,你需要创建一个自定义的数据类型。 这段时间,您可以创建一些TypeScript称为Interface东西。

In your root directory, create a directory and name it types. Inside this new directory, create a new file named, index.ts. You can declare a new interface with the interface keyword; it is considered best practice to make these CamelCase.

在您的根目录中,创建一个目录并命名为types 。 在这个新目录中,创建一个名为index.ts的新文件。 您可以使用interface关键字声明一个新接口; 制作这些CamelCase被认为是最佳实践。

types/index.ts
类型/ index.ts
export interface User {

}

From here, you can start defining the properties and value types that the object will have.

从这里开始,您可以开始定义对象将具有的属性和值类型。

types/index.ts
类型/ index.ts
export interface User {
  firstName: string,
  lastName: string,
  twitterHandle: string,
  location: {
    city: string,
    state: string
  }
}

In this example, we have an interface with an object inside it (location). We can break this up further by nesting interfaces. We can also make any property optional by adding a ? to it. This means that this property may or may not have a value.

在这个例子中,我们有一个接口,其中有一个对象( location )。 我们可以通过嵌套接口来进一步分解。 我们还可以通过添加?将任何属性设为可选? 对它。 这意味着此属性可能有值也可能没有值。

types/index.ts
类型/ index.ts
export interface User {
  firstName: string,
  lastName: string,
  twitterHandle?: string,
  location: Location
}

export interface Location {
  city: string,
  state: string
}

We can now use this custom data type in any Single-File Vue Component (.vue) or TypeScript (.ts) file.

现在,我们可以在任何单文件Vue组件( .vue )或TypeScript( .ts )文件中使用此自定义数据类型。

在单文件Vue组件(SFC)中使用自定义数据类型 (Using Custom Data Types in Single-File Vue Components (SFCs))

Now that we have your interface created, we can import this into our SFC like any other ESM, JavaScript file, etc. In order to use TypeScript in our component, you will need to add a lang attribute to the script tag of your component. The value of that attribute should be ts.

现在我们已经创建了interface ,我们可以像将其import到SFC中一样,将其import其他SSM,JavaScript文件等。为了在组件中使用TypeScript,您需要向组件的script标签添加lang属性。 该属性的值应为ts

When using TypeScript in single-file Vue components, the Vue library must be imported so you can extend from it. Since we are not using the class-style syntax, you use the as keyword to declare data as a data type.

在单文件Vue组件中使用TypeScript时,必须导入Vue库,以便可以对其进行扩展。 由于我们没有使用类样式的语法,因此可以使用as关键字将数据声明为数据类型。

App.vue
应用程序
<template>
  <p>{{ user.firstName }}</p>
</template>

<script lang="ts">
  import Vue from 'vue'
  import { User } from '@/types' // Our interface

  export default Vue.extend({
    name: 'Home' as string,
    data() {
      return {
        user: {} as User // Declaring reactive data as type User
      }
    },
    mounted() {
      this.user = {
        firstName: `Dave`,
        lastName: `Berning`,
        twitterHandle: `@daveberning`,
        location: {
          city: `Cincinnati`,
          state: `OH`
        }
      }
    }
  })
</script>

For things like const, let, var, or a function return type, you can define it’s type with the colon :.

对于constletvar或函数返回类型之类的东西,可以用冒号定义它的类型:

App.vue
应用程序
<script lang="ts">
  import Vue from 'vue'
  import { User } from '@/types'

  export default Vue.extend({
    name: 'Home' as string,
    data() {
      return {
        user: {} as User
      }
    },
    computed: {
      fullName(): string { // Computed Property returns a string
        return `${this.user.firstName} ${this.user.lastName}`
      }
    },
    mounted(): void { // The mounted hook returns nothing
      ...
    }
  })
</script>

申报文件 (Declaration Files)

After generating your Vue project from the command line, you might have noticed the shims-vue.d.ts file. That is declaration file (.d.ts). A declaration file is a file that does not contain any executable code, but contains descriptions of code that exists outside of the project files.

从命令行生成Vue项目后,您可能已经注意到shims-vue.d.ts文件。 那就是声明文件( .d.ts )。 声明文件是一个不包含任何可执行代码,但包含项目文件之外的代码说明的文件。

These are useful when using Node modules that do not contain any TypeScript interfaces, types, or declaration files. In a sense, the only purpose for these files are to tell TypeScript how to handle external code.

当使用不包含任何TypeScript接口,类型或声明文件的Node模块时,这些功能很有用。 从某种意义上说,这些文件的唯一目的是告诉TypeScript如何处理外部代码。

shims.d.ts
垫片
declare module '*.vue' {
  import Vue from 'vue'
  export default Vue
}

So in this case, we are essentially telling the TypeScript compiler (and the IDE) how to handle .vue files; a framework-specific file with HTML, CSS, and TS.

因此,在这种情况下,我们实际上是在告诉TypeScript编译器(和IDE)如何处理.vue文件。 具有HTML,CSS和TS的特定于框架的文件。

结论 (Conclusion)

TypeScript is to JavaScript as SASS is to CSS; TypeScript is JavaScript. With TypeScript, you can be as strict or as lenient as you want. It’s a great Open Source language that helps keep your code base consistent and scalable as your project continues to grow.

TypeScript适用于JavaScript,SASS适用于CSS。 TypeScript 是 JavaScript。 使用TypeScript,您可以根据需要严格或宽容。 这是一种很棒的开源语言,可以随着项目的不断发展,帮助您保持代码库的一致性和可伸缩性。

TypeScript is also heavily integrated with various popular IDEs and editors including: VS Code, WebStorm, Sublime, Vim, Atom, and more. With these editors, TypeScript works in the background, behind the scenes to provide real-time clues, suggestions, and previews of function arguments and return types.

TypeScript还与各种流行的IDE和编辑器高度集成,包括:VS Code,WebStorm,Sublime,Vim,Atom等。 使用这些编辑器,TypeScript在后台,幕后工作,以提供功能参数和返回类型的实时线索,建议和预览。

All in all, it’s a language that continues to find it’s way into more tools, libraries, and frameworks that developers use everyday. It has a strong Open Source community and the backing of Microsoft.

总而言之,它是一种语言,并不断地将其引入开发人员日常使用的更多工具,库和框架中。 它拥有强大的开放源代码社区和Microsoft的支持。

翻译自: https://www.digitalocean.com/community/tutorials/vuejs-using-typescript-with-vue

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值