详解Vue3.0 前的 TypeScript 最佳入门实践

2020-06-14 06:02:51易采站长站整理
.vue 文件都按
VueConstructor<Vue>
处理。

此时我们打开亲切的

src/components/HelloWorld.vue
,将会发现写法已大有不同


<template>
<div class="hello">
<h1>{{ msg }}</h1>
<!-- 省略 -->
</div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';

@Component
export default class HelloWorld extends Vue {
@Prop() private msg!: string;
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped></style>

至此,准备开启新的篇章

TypeScript
极速入门 和
vue-property-decorator

3. TypeScript 极速入门

3.1 基本类型和扩展类型

Typescript
Javascript
共享相同的基本类型,但有一些额外的类型。

元组

Tuple

枚举
enum

Any
Void

1. 基本类型合集


// 数字,二、八、十六进制都支持
let decLiteral: number = 6;
let hexLiteral: number = 0xf00d;

// 字符串,单双引都行
let name: string = "bob";
let sentence: string = `Hello, my name is ${ name }.

// 数组,第二种方式是使用数组泛型,Array<元素类型>:
let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3];

let u: undefined = undefined;
let n: null = null;

2. 特殊类型

1. 元组

Tuple

想象 元组 作为有组织的数组,你需要以正确的顺序预定义数据类型。


const messyArray = [' something', 2, true, undefined, null];
const tuple: [number, string, string] = [24, "Indrek" , "Lasn"]

如果不遵循 为元组 预设排序的索引规则,那么

Typescript
会警告。

​ (

tuple
第一项应为
number
类型)

2. 枚举