美文网首页
Vue2.x中使用ts

Vue2.x中使用ts

作者: Betterthanyougo | 来源:发表于2020-05-29 22:40 被阅读0次

范例,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
    }
}

相关文章

网友评论

      本文标题:Vue2.x中使用ts

      本文链接:https://www.haomeiwen.com/subject/dmkqzhtx.html