References
Vue official documentation-TypeScript support
Code address
New Project
vue create vue-ts
cd vue-ts
vue add @vue/typescript
Project configuration, you can refer to this article in the Vue + TypeScript project, and how to configure ESLint Prettier
Type annotations and compile-time type checking
Type annotation: use colon + type after the variable to do type annotation
// test.ts
let title1: string; // 类型注解
title1 = "xbl"; // 正确
title1 = 4; // 错误
let title2 = "xx"; // 类型推论
title2 = 2;// 错误
//数组类型
let names: string[];
names = ['Tom'];//或Array<string>
//任意类型
let foo:any;
foo = 'xx'
foo = 3
//any类型也可用于数组
let list: any[];
list = [1, true, "free"];
list[1] = 100;
//函数中使用类型
function greeting(person: string): string {
return 'Hello, ' + person;
}
//void类型,常用于没有返回值的函数
function warnUser(): void { alert("This is my warning message"); }
function
Mandatory parameter: Once the parameter is declared, it needs to be passed, and the type must conform to
function greeting(person: string): string {
return "Hello, " + person;
}
greeting('tom')
Optional parameters: The parameter name is followed by a question mark to become an optional parameter
function greeting(person: string, msg?: string): string {
return "Hello, " + person;
}
Parameter default
function greeting(person: string, msg = ''): string {
return "Hello, " + person;
}
Function overloading
// 声明1
function info(a: {name: string}): string;
// 声明2
function info(a: string): {name: string};
// 实现
function info(a: {name: string} | string): {name: string} | string {
if (typeof a === "object") {
return a.name;
} else {
return { name: a };
}
}
console.log(info({ name: "tom" }));
console.log(info("tom"));
class
Class characteristics
The classes in ts are roughly the same as in es6, and here we focus on the features brought by ts
class MyComp {
private _foo: string; // 私有属性,不能在类的外部访问
protected bar: string;// 保护属性,可以在子类中访问
// 构造函数参数加修饰符,能够定义为成员属性
constructor(public tua = "tua") {}
// 方法也有修饰符
private someMethod() {}
// 存取器:属性方式访问,可添加额外逻辑,控制读写性
get foo() { return this._foo }
set foo(val) { this._foo = val }
}
interface
The interface only constrains the structure, does not require implementation, and is easier to use
interface Person {
firstName: string;
lastName: string;
}
function greeting(person: Person) {
return 'Hello, ' + person.firstName + ' ' + person.lastName;
}
const user = {firstName: 'Jane', lastName: 'User'};
console.log(user);
console.log(greeting(user));
Generic
Generics (Generics) mean that when a function, interface or class is defined, a specific type is not specified in advance, but
a characteristic of the type is specified when it is used . This increases code versatility.
// 不用泛型
// interface Result {
// ok: 0 | 1;
// data: Feature[];
// }
// 使用泛型
interface Result<T> {
ok: 0 | 1;
data: T;
}
// 泛型方法
function getData<T>(): Result<T> {
const data: any = [
{ id: 1, name: "类型注解", version: "2.0" },
{ id: 2, name: "编译型语言", version: "1.0" }
];
return { ok: 1, data }
}
Decorator
Decorators are used to extend a class or its properties and methods. @xxx is how to write the decorator
Component declaration: @Component
A typical application is the component decorator @Component
@Component
export default class Hello extends Vue {}
Property declaration: @Prop
In addition to declaring in @Component, you can also declare component properties by @Prop
export default class HelloWorld extends Vue {
// Props()参数是为vue提供属性选项
// !称为明确赋值断言,它是提供给ts的
@Prop({type: String, required: true})
private msg!: string;
}
Event handling: @Emit
Dispatch event notification when new features are added, Hello.vue
@Emit()
private addFeature(event: any) {// 若没有返回值形参将作为事件参数
const feature = { name: event.target.value, id: this.features.length + 1 };
this.features.push(feature);
event.target.value = "";
return feature;// 若有返回值则返回值作为事件参数
}
Change monitoring: @Watch
@Watch('msg')
onRouteChange(val:string, oldVal:any){
console.log(val, oldVal);
}
vuex use: vuex-class
vuex-class provides Vuex state binding help method for vue-class-component.
Install dependencies
npm i vuex-class -S
Define the state, store.ts
import Vuex from "vuex";
import Vue from "vue";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
features: [
{ id: 1, name: "类型", version: "1.0" },
{ id: 2, name: "编译型语言", version: "1.0" },
],
},
mutations: {
addFeatureMutation(state: any, featureName) {
state.features.push({ id: state.features.length + 1, name: featureName });
},
},
actions: {
addFeatureAction({ commit }, featureName) {
commit("addFeatureMutation", featureName);
},
},
});
Use, Hello.vue
import { State, Action, Mutation } from "vuex-class";
@Component
export default class Feature extends Vue {
// 状态、动作、变更映射
@State features!: string[];
@Action addFeatureAction: any;
@Mutation addFeatureMutation: any;
private addFeature(event) {
console.log(event);
// this.features.push(event.target.value);
this.addFeatureAction(event.target.value);
// this.addFeaturMutation(event.target.value);
event.target.value = "";
}
}
Decorator principle
Class decorator
//类装饰器表达式会在运行时当作函数被调用,类的构造函数作为其唯一的参数。
function log(target: Function) {
// target是构造函数
console.log(target === Foo); // true
target.prototype.log = function() {
console.log(this.bar);
}
// 如果类装饰器返回一个值,它会使用提供的构造函数来替换类的声明。
}
@log
class Foo {
bar = 'bar'
}
const foo = new Foo();
// @ts-ignore
foo.log();
Method decorator
function dong(target: any, name: string, descriptor: any) {
// 这里通过修改descriptor.value扩展了bar方法
const baz = descriptor.value;
descriptor.value = function(val: string) {
console.log('dong~~');
baz.call(this, val);
}
return descriptor
}
class Foo {
@dong
setBar(val: string) {
this.bar = val
}
}
foo.setBar('lalala')
Attribute decorator
// 属性装饰器
function mua(target, name) {
target[name] = 'mua~~~'
}
class Foo {
@mua ns!:string;
}
console.log(foo.ns);
A little modification to make it accept parameters
function mua(param:string) {
return function (target, name) {
target[name] = param
}
}
Take a look at Component and create a new Decor.vue
<template>
<div>{{msg}}</div>
</template>
<script lang='ts'>
import { Vue } from "vue-property-decorator";
function Component(options: any) {
return function(target: any) {
return Vue.extend(options);
};
}
@Component({
props: {
msg: {
type: String,
default: ""
}
}
})
export default class Decor extends Vue {}
</script>