Let's embrace the powerful TypeScript together--Ts+Vue complete tutorial

Function

  •  carousel
  •  search
  •  list
  •  lazy loading
  •  simple animation
  •  loading
  •  vue-router.ts
  •  vuex.ts
  •  vue-class-component uses
  •  vuex-class use
  •  xxx.d.ts declaration file
  •  Class-based writing
  •  mock data
  •  tsconfig.json
  •  webpack configuration
  •  vue-typescript-cli

Simple example when done

Class-based writing plus static type checking, can't be more hilarious

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { State } from "vuex-class";

@Component
export default class Shops extends Vue {
  @State shops: StoreState.shop[];
  @State searchVal: string;

  get shopList(): StoreState.shop[] {
    const shops = this.shops;
    const searchVal = this.searchVal;
    return shops.filter(
      (el: StoreState.shop) => el.shopName.indexOf(searchVal) > -1
    );
  }
}
</script>

Superset of JavaScript

Supports all native JavaScript syntax

strongly typed language

Many mainstream languages ​​are now strongly typed, and this has always been the place where JavaScript has been criticized. After using TypeScript, you will save a lot of time in code debugging, refactoring and other steps.

For example, when a function returns a value, it may undergo complex operations. If we want to know the structure of this value, we need to read this code carefully. Then if you have TypeScript, you can directly see the return value structure of the function, which will be very convenient

Powerful IDE support

The current mainstream editors such as VSCode, WebStorm, , Atom, Sublimeetc. have very friendly support for TypeScript, mainly reflected in the intelligent prompt, which is very convenient

Runs on any browser, computer, operating system

Powerful compilation engine

Iterative update is fast

Constantly updated to provide more convenient and friendly Api

Microsoft and Google Dad

TypeScript is a language developed by Microsoft, and Google Angularuses TypeScript, so don't worry about stopping maintenance, at least in the next few years, TypeScript will be a mainstream development language

npm downloads are very high

As of 2017.12.17, the average daily downloads of TypeScript on npm around the world are 30wabout 10 times that of Vue. It can be seen that TypeScript is still very popular.

TypeScript configuration

This project has been configured, here is a record of the pit-stepping process at that time

1. Webpack

首先需要安装ts-loader,这是TypeScript为Webpack提供的编译器,类似于babel-loader

npm i ts-loader -D

接着在Webpack的module.rules里面添加对ts的支持(我这里的webpack版本是2.x):

{
    test: /\.vue$/,
    loader: 'vue-loader',
    options: vueLoaderConfig
},
{
    test: /\.tsx?$/,
    exclude: /node_modules/,
    use: [
      "babel-loader",
      {
        loader: "ts-loader",
        options: { appendTsxSuffixTo: [/\.vue$/] }
      }
    ]
}

2. tsconfig.json

创建tsconfig.json文件,放在根目录下,和package.json同级

配置内容主要也看个人需求,具体可以去typescript的官网查看,但是有一点需要注意:

在Vue中,你需要引入 strict: true (或者至少 noImplicitThis: true,这是 strict 模式的一部分) 以利用组件方法中 this 的类型检查,否则它会始终被看作 any 类型。

这里列出我的配置,功能在注释中给出

{
  "include": [
    "src/*",
    "src/**/*"
  ],
  "exclude": [
    "node_modules"
  ],
  "compilerOptions": {
    // types option has been previously configured
    "types": [
      // add node as an option
      "node"
    ],
    // typeRoots option has been previously configured
    "typeRoots": [
      // add path to @types
      "node_modules/@types"
    ],
    // 以严格模式解析
    "strict": true,
    // 在.tsx文件里支持JSX
    "jsx": "preserve",
    // 使用的JSX工厂函数
    "jsxFactory": "h",
    // 允许从没有设置默认导出的模块中默认导入
    "allowSyntheticDefaultImports": true,
    // 启用装饰器
    "experimentalDecorators": true,
    "strictFunctionTypes": false,
    // 允许编译javascript文件
    "allowJs": true,
    // 采用的模块系统
    "module": "esnext",
    // 编译输出目标 ES 版本
    "target": "es5",
    // 如何处理模块
    "moduleResolution": "node",
    // 在表达式和声明上有隐含的any类型时报错
    "noImplicitAny": true,
    "lib": [
      "dom",
      "es5",
      "es6",
      "es7",
      "es2015.promise"
    ],
    "sourceMap": true,
    "pretty": true
  }
}

3. 修改main.js

  1. 把项目主文件main.js修改成main.ts,里面的写法基本不变,但是有一点需要注意: 引入Vue文件的时候需要加上.vue后缀,否则编辑器识别不到

  2. 把webpack的entry文件也修改成main.ts

4. vue-shims.d.ts

TypeScript并不支持Vue文件,所以需要告诉TypeScript*.vue文件交给vue编辑器来处理。解决方案就是在创建一个vue-shims.d.ts文件,建议放在src目录下再创建一个typings文件夹,把这个声明文件放进去,如:src/typings/vue-shims.d.ts,文件内容:

*.d.ts类型文件不需要手动引入,TypeScript会自动加载

declare module '*.vue' {
  import Vue from 'vue'
  export default Vue
}

到这里TypeScript在Vue中配置就完成了,可以愉快的撸代码了~

第三方插件库

现在Vue官方已经明确提出支持TypeScript,并考虑出一个对应的vue-cli,在这之前,Vue开发团队已经开发出了一些插件库来支持TypeScript,这里简单和大家介绍一下。

Vue-Class-Component

vue-class-component是官方维护的TypeScript装饰器,写法比较扁平化。Vue对其做到完美兼容,如果你在声明组件时更喜欢基于类的 API,这个库一定不要错过

ps:用了这个装饰器之后写方法不需要额外加逗号,贼嗨~~~

import Vue from "vue";
import Component from "vue-class-component";

@Component
export default class App extends Vue {
  name:string = 'Simon Zhang'

  // computed
  get MyName():string {
    return `My name is ${this.name}`
  }

  // methods
  sayHello():void {
    alert(`Hello ${this.name}`)
  }

  mounted() {
    this.sayHello();
  }
}

这个代码如果用原生Vue语法来写的话就是这样:

export default {
  data () {
    return {
      name: 'Simon Zhang'
    }
  },

  mounted () {
    this.sayHello()
  },

  computed: {
    MyName() {
      return `My name is ${this.name}`
    }
  },

  methods: {
    sayHello() {
      alert(`Hello ${this.name}`)
    },
  }
}

Vuex-Class

vuex-class是基于基于vue-class-component对Vuex提供的装饰器。它的作者同时也是vue-class-component的主要贡献者,质量还是有保证的。

import Vue from "vue";
import Component from "vue-class-component";
import { State, Action, Getter } from "vuex-class";

@Component
export default class App extends Vue {
  name:string = 'Simon Zhang'
  @State login: boolean;
  @Action initAjax: () => void;
  @Getter load: boolean;

  get isLogin(): boolean {
    return this.login;
  }

  mounted() {
    this.initAjax();
  }
}

上面的代码就相当于:

export default {
  data() {
    return {
      name: 'Simon Zhang'
    }
  },

  mounted() {
    this.initAjax()
  },

  computed: {
    login() {
      return this.$store.state.login
    },
    load() {
      return this.$store.getters.load
    }
  },

  methods: {
    initAjax() {
      this.$store.dispatch('initAjax')
    }
  }
}

Vue-Property-Decorator

vue-property-decorator 是在 vue-class-component 上增强了更多的结合 Vue 特性的装饰器,新增了这 7 个装饰器

  • @Emit
  • @Inject
  • @Model
  • @Prop
  • @Provide
  • @Watch
  • @Component (从 vue-class-component 继承)

引入部分第三方库的时候需要额外声明文件

比如说我想引入vue-lazyload,虽然已经在本地安装,但是typescript还是提示找不到模块。原因是typescript是从node_modules/@types目录下去找模块声明,有些库并没有提供typescript的声明文件,所以就需要自己去添加

解决办法:在src/typings目前下建一个tools.d.ts文件,声明这个模块即可

declare module 'vue-awesome-swiper' {
  export const swiper: any
  export const swiperSlide: any
}

declare module 'vue-lazyload'

对vuex的支持不是很好

在TypeScript里面使用不了mapState、mapGetters等方法,只能一个变量一个变量的去引用,这个要麻烦不少。不过使用vuex-class库之后,写法上也还算简洁美观

export default class modules extends Vue {
  @State login: boolean; // 对应this.$store.state.login
  @State headline: StoreState.headline[]; // 对应this.$store.state.headline

  private swiperOption: Object = {
    autoplay: true,
    loop: true,
    direction: "vertical"
  };

  logoClick(): void {
    alert("点我干嘛");
  }
}

总结

TypeScript还是非常值得学习和使用一个语言,还是有很多优点的

欢迎大家对我的项目提建议,欢迎Star~

QQ交流群:323743292

Build Setup

# 安装依赖
npm install

# 启动项目
npm run dev

# 打包项目
npm run build

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325423553&siteId=291194637