Typescript由于其更多的规则,类型限制,代码更高的可预测性,可控性和可维护性,近2年发展迅速,React和Angular底层已经用TS重写,vue3.0预计在2020也会用TS重写,但是很多开发者已经蠢蠢欲动了。

vue-cli3.0已经支持typescript配置,脚手架已经把该配置的给配置好了。
vue-cli3.0不再直接暴露webpack相关配置,如果需要个性化配置需要在vue.config.js中完成,与开发环境相关的需要在根目录下创建对应的配置文件,比如测试环境.env.pro_test,正式环境.env.production,具体可参考官方文档:https://cli.vuejs.org/zh/guide/

路由配置

import Vue from "vue";
import VueRouter from "vue-router";
import Home from "@/views/Home.vue";

Vue.use(VueRouter);

function importComponent(component: string): Object {
  return () => import(/* webpackChunkName: "about" */ "@/views/" + component);
}
const routes = [
  {
    path: "/",
    name: "home",
    component: Home
  },
  {
    path: "/about",
    name: "about",
    component: importComponent("About")
  }
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes
});

export default router;

单文件组件

<template>
  <div class="home">
    <h1>hello,{{ fullName }}</h1>
    <h2>{{ user.age }}</h2>
  </div>
</template>

<script lang="ts">
interface User {
  firstName: string;
  age: number;
  lastName: string;
}
export default {
  name: "home",
  data() {
    return {
      user: {
        firstName: "Black",
        lastName: "Jack",
        age: 20
      }
    };
  },
  computed: {
    fullName(): string {
      return this.user.firstName + " " + this.user.lastName;
    }
  }
};
</script>
<style lang="scss">
.home {
  h1 {
    font-size: 40px;
  }
}
</style>

有脚手架的帮助,省去了大量配置与转换工作,开发者只需要在实现业务需求上遵循Typesrcript语法即可,有了eslint,typescript在变量类型上的约束,可以大大减少错误率,还是比较方便的。
效果如下:
image.png


沉默术士
29 声望1 粉丝