TypeScript 在Vue中的实践

Author:KK姐html

ts有什么用

类型检查, 拥抱es6,支持部分的esNext草案,直接编译到原生js、引入新的语法糖vue

为何用ts

TypeScript的设计目的应该是解决JavaScript的“痛点”:弱类型和没有命名空间,致使很难模块化,不适合开发大型程序。另外它还提供了一些语法糖来帮助你们更方便地实践面向对象的编程。es6

typescript不只能够约束咱们的编码习惯,还能起到注释的做用,当咱们看到一函数后咱们立马就能知道这个函数的用法,须要传什么值,返回值是什么类型一目了然,对大型项目的维护性有很大的提高。vuex

编译报错, 会生成编译结果么?

答案是确定的,固然能够在tsconfig.json的配置, noEmitONErrortypescript

tsconfig.json的文件配置

还没搞定npm

基础总结

数据类型
  • boolean 、number、string、null、 undefined、 Symbol
  • undefined 和null 类型的数据只能被赋值undefined 和null, 可是这个类型是全部类型的子类型
  • void 空类型
// undefined和null是全部类型子类型,均可以赋值
    let num: Symbol = undefined;ss
    let num: number = undefined;
    // undefined类型, 只能给undefined
    let u: undefined = undefined; 
    let n: null = null;
复制代码
  • any和类型推断
// 在ts中,变量在声明的时候,若是没有定义其类型,会被识成默认类型 
   let str;
   str = 'I am strgting';
   str = 1024;
   // 未定义类型,直接赋值
   let num= 124; 
   // 等同于 let num:number = 124, 在后面代码若是赋予num一个string会被报错
   
   
复制代码
多个可能属性
//只能访问可能属性的共有属性
    function getLength(param: string| number) {
        return param.length;
    }
    // 会报错, 由于 length不是 sting和number类型的共有属性
    // 技巧--》 使用类型别名
    type possibleType = string | number;
    function getLength(param: possibleType) {
        return param.length;
    }
复制代码
接口的概念
  • 在ts中,interface包括对行为的抽象,由类去实现(implements)
  • 也包括对对象轮廓的描述
对象interface -》动态属性

必选参数和可选参数的类型是动态属性类型的子集,全部在动态属性类型设置的时候要设置上全部类型编程

interface userinfo {
    "memberId": number,
    "uName": string,
    "employeeId": string,
    "datetime": string,
    "platformList"?: Array<platform>,
    [propName: string]: string | number | Array<platform> | undefined
  }
复制代码
只读属性的约束力

注意点: 只读属性的约束力在于第一次给对象赋值的时候,而不是给属性赋值的时候 readonly和 const的区别: const是变量, readonly是属性json

接口-》抽象方法的实现
export interface ISRequest {
      fetch(url: string, arg?: Object, callback?: Function): Promise<Object>;
    }
    
    export class SafeRequest implements ISRequest {
          public async fetch(url: string, arg, callback?: Function): Promise<Object> {
            return new Promise((resolve, reject) => {
                
            })
    }
复制代码
用接口表示数组
interface NumberArray {
        [index: any]: number
    }
    let numArr: NumberArray = [1, 2, 3]
复制代码
函数的类型
  • 可选参数, 必须在必选参数后面
  • 参数默认值
function buildName(firstName: string, lastName?: string) {
        
    }
复制代码
  • 添加默认值的参数识别为可选参数
  • 剩余参数
类型断言
// <类型>值
   // 值 as 类型
复制代码
疑惑--》 声明文件

当使用第三方库时,咱们须要引用它的声明文件,才能得到对应的代码补全、接口提示等功能。数组

声明文件在哪里?
  • 与npm包绑定在一块儿
  • npm包的维护者并无提供声明文件, 只能由其余人将声明文件发布到@types里面
  • 本身写个声明文件
npm包的声明文件 和全局变量的声明文件

在 npm 包的声明文件中,使用 declare 再也不会声明一个全局变量,而只会在当前文件中声明一个局部变量。只有在声明文件中使用 export 导出,而后在使用方 import 导入后,才会应用到这些类型声明。 ######declare global 使用 declare global 能够在 npm 包或者 UMD 库中扩展全局变量的类型bash

内置对象

内置对象查询--》点击
ESMAScript提供了Boolean、Error、Date、RegExp

interface obj = {
        param: Function
        param: Promise
    }
复制代码
枚举--》 数据的双向映射
enum companyList= {1: 'aaa', 2: 'bbb'}
    var companyList = {
        1: 'aaa',
        2: 'bbb',
        aaa: 1,
        bbb: 2
    }
复制代码
Vue in Typescript
三大利器
  • vue-component-class
    • 方法能够直接声明为类成员方法。
    • 能够将计算属性声明为类属性访问器。
    • 默认data被看成类属性
    • data , render 和vue的生命周期的钩子直接是类成员的方法,保留这些命名,不要冲突
    • 对于其余的配置项,例如prop、componets等传递给装饰器函数
import Vue from 'vue';
    import Component from 'vue-componet-class';
    Component.resgisterHooks([
        'beforeRouteEnter'
    ])
    @Componnet({
        props: {
            
        },
        components: {
            
        }
    })
    export default class App extends Vue {
        // aa = '';
        // 类型推断aa是个string, 后面aa只能赋值aa类型
        // 因此最好使用先声明后
        
        // data
       public tableModelItems: Array<any>;
       constructor() {
           super();
           this.tableModelItems = [];
       }
       // computed
      public get filterTableData() {
		return this.tableData.filter((i: any) => i.refundStatus === 0).length
		
		// 方法
		// 声明周期
		
		// 此时须要路由函数的生命周期钩子咋办
		beforeRouteEnterf() {
		    next() // 必定要写,不然玩不下去,为何?
		}
	}
        
        
    }
复制代码
- vue-property-decorator(依赖vue-component-class提供了更多了装饰器,代码更加显示 )
    - @Emit
    - @Inject
    - @Prop
    - @Provide
    - @Watch
- vuex-class(链接了vue和vuex)
    
```js
    
复制代码

还没搞定的bug

错误--》 类型报错

添加script的类型

<script lang="ts"></script>
    <!--不然下面的类型报错-->
复制代码
错误之--》Vue中挂载propoty出错(若是仍是爆红,重启ide)

声明再挂载

<!--inject-->
    import _Vue from 'vue'
    import moment from "moment";
    export default {
      install(Vue: typeof _Vue, options: any) {
        Vue.prototype.$moment = moment;
        Vue.prototype.$log = () => {
          console.log(new Date())
        }
      }
    }
<!--types-->
    import Vue from 'vue'
    declare module 'vue/types/vue' {
      interface Vue {
        $moment: Function
        $log: Function
      }
    }
复制代码
ts中不能识别.vue文件

TypeScript 默认只识别 .ts 文件,不识别 .vue 文件, 乖乖的写 import Component from 'components/component.vue'

vuex-class的Emit传参数给父组件报错
@emit("reset")
    reset(role, this.formData){}
    <!--此时报错-->
    
复制代码

错误--> 可选参数爆红

参考连接

相关文章
相关标签/搜索