Vue2.x中使用ts

范例,HelloWorld.vue

<template>
  <div>
    <!-- 新增 -->
    <input type="text" @keyup.enter="addFeature" />
    <div v-for="item in features" :key="item.id" :class="{selected: item.selected}">{{ item.name }}</div>
    <div>{{count}}</div>
  </div>
</template>

<script lang="ts">
// import { Vue } from "vue-property-decorator";
import { Vue, Component, Prop, Emit, Watch } from "vue-property-decorator";
import { FeatureSelect } from "@/types";

// 泛型方法
function getList<T>(): Promise<T> {
  return Promise.resolve([
    { id: 1, name: "类型注解", selected: false },
    { id: 2, name: "编译型语言", selected: true }
  ] as any);
}

@Component
export default class HelloWorld extends Vue {

  // 括号里面是传给vue的配置
  @Prop({type: String, required: true})
  msg!: string;
  
  // message = 'class based component'
  // ts特性展示,!是赋值断言,表示该属性一定会被赋值,编译器不用警告
  features: FeatureSelect[] = [];

  // 生命周期直接用同名方法即可
  async created() {
    // this.features = await getList<FeatureSelect[]>();
    const resp = await this.$axios.get<FeatureSelect[]>('/api/list')
    this.features = resp.data
    
  }

  @Watch('msg')
  onMsgChange(val:string, old:string) {
    console.log(val);
  }

  // 回调函数直接声明即可
  @Emit('add-feature')
  addFeature(e: KeyboardEvent) {
    // 断言为Input,一般当一些类型需要变得更具体的时候需要使用as断言
    // 这里把EventTarget类型断言为它的子类HTMLInputElement
    // 通常编程者比编译器更清楚自己在干什么
    const inp = e.target as HTMLInputElement;
    const feature: FeatureSelect = {
      id: this.features.length + 1,
      name: inp.value,
      selected: false
    };
    this.features.push(feature);

    inp.value = "";
    // 返回值作为事件参数
    return feature
  }

  // 访问器当做计算属性
  get count() {
    return this.features.length;
  }
}
</script>

<style scoped>
.selected {
  background-color: rgb(205, 250, 242);
}
</style>

声明文件

使用ts开发时如果要使用第三方js库的同时还想利用ts诸如类型检查等特性就需要声明文件,类
似 xx.d.ts
同时,vue项目中还可以在shims-vue.d.ts中对已存在模块进行补充
npm i @types/xxx

范例:利用模块补充$axios属性到Vue实例,从而在组件里面直接用

 
// main.ts
import axios from 'axios'
Vue.prototype.$axios = axios;
 
// shims-vue.d.ts
import Vue from "vue";
import { AxiosInstance } from "axios";
declare module "vue/types/vue" {
  interface Vue {
    $axios: AxiosInstance;
  }
}

范例:给krouter/index.js编写声明文件,index.d.ts

 
import VueRouter from "vue-router";
declare const router: VueRouter
export default router

装饰器

装饰器用于扩展类或者它的属性和方法。@xxx就是装饰器的写法
常见的有@Prop,@Emit,@Watch
具体使用见文章开头的例子

状态管理推荐使用:vuex-module-decorators

vuex-module-decorators 通过装饰器提供模块化声明vuex模块的方法,可以有效利用ts的类型系
统。
安装

npm i vuex-module-decorators -D

根模块清空,修改store/index.ts

export default new Vuex.Store({})

定义counter模块,创建store/counter

import { Module, VuexModule, Mutation, Action, getModule } from 'vuex-module-
decorators'
import store from './index'
// 动态注册模块
@Module({ dynamic: true, store: store, name: 'counter', namespaced: true }) class CounterModule extends VuexModule {
count = 1
  @Mutation
  add() {
// 通过this直接访问count
    this.count++
  }
// 定义getters
get doubleCount() {
    return this.count * 2;
  }
  @Action
  asyncAdd() {
setTimeout(() => {
// 通过this直接访问add this.add()
}, 1000);
 
} }
// 导出模块应该是getModule的结果
export default getModule(CounterModule)
使用,App.vue
  <p @click="add">{{$store.state.counter.count}}</p>
<p @click="asyncAdd">{{count}}</p>
 
import CounterModule from '@/store/counter'
@Component
export default class App extends Vue {
  get count() {
    return CounterModule.count
}
  add() {
    CounterModule.add()
}
  asyncAdd() {
    CounterModule.asyncAdd()
} }

装饰器原理

装饰器是工厂函数,它能访问和修改装饰目标。
类装饰器,07-decorator.ts

 
//类装饰器表达式会在运行时当作函数被调用,类的构造函数作为其唯一的参数。 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();

方法装饰器

 
function rec(target: any, name: string, descriptor: any) { // 这里通过修改descriptor.value扩展了bar方法
const baz = descriptor.value;
descriptor.value = function(val: string) {
        console.log('run method', name);
        baz.call(this, val);
    }
}
class Foo {
  @rec
  setBar(val: string) {
    this.bar = val
} }
foo.setBar('lalala')

属性装饰器

// 属性装饰器
function mua(target, name) {
    target[name] = 'mua~~~'
}
class Foo {
  @mua ns!:string;
}
console.log(foo.ns);

稍微改造一下使其可以接收参数

function mua(param:string) {
    return function (target, name) {
        target[name] = param
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,519评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,842评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,544评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,742评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,646评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,027评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,513评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,169评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,324评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,268评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,299评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,996评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,591评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,667评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,911评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,288评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,871评论 2 341