1. 实现Typescript的Vue组件。
- 以Types组件为例改写
- TS写法,用class组件写data methods 和生命周期
- 起手
export default class Types extends Vue {
}
- Component修饰符,在最上面加@Compo按下tab键,选择从vue-property-decorator引入
import {Component} from "vue-property-decorator"
@Component
export default class Types extends Vue {
}
- 必需制定参数type的类型
selectType(type: string) { // type 只能是 '-' 和 '+' 中的一个
}
- 代码总结
import Vue from 'vue'
import {Component} from "vue-property-decorator"
@Component
export default class Types extends Vue {
type = '-' // '-'表示支出.'+'表示收入
selectType(type: string) { // type 只能是 '-' 和 '+' 中的一个
if(type !== '-' && type !== '+'){
throw new Error('type is unknown')
}
this.type = type
}
created(){}
mounted(){}
}
- props用法
1 查看一个包的最新版本,在终端输入 npm info typescript version
2. TS 组件 @Prop装饰器
// 左边Number是运行时的检查,右边number是编译时的检查,编译时的检查会在写代码的时候就给提示
@Prop(Number) xxx: number | undefined;
// Prop 告诉 Vue xxx 不是 data 是 prop
// Number 告诉 Vue xxx 运行时类型 是个 Number
// xxx 属性名
// number | undefined 就是 告诉 TS xxx 的编译时类型
// 为什么前面的Number是大些后面是小写,见3.编译时和运行时的区别
- TS的好处
- html直接空格告诉你有哪些参数
- 如果声明了类型,代码写错了会提前告诉,编译报错,无法编程js
- 检查调用的方法到底能不能调用,你不能写.tostring
3. 编译时和运行时的区别
4. TS的本质
5. Vue但文件组件的三种写法
- 用JS对象
export default { data,props,methods,created,... }
- 用 TS 类