在 vue 中使用 typescript

构建项目

通过官方脚手架构建安装

#  如果没有安装 Vue CLI 就先安装
npm install --global @vue/cli

安装后运行 vue create my-app,进入项目选择预设界面,确保选择 typescript、babel 选项。eslint 使用的是 standard 标准。

使用插件

首先需要了解一下在 vue 中常用的 typescript 库:

  • vue-class-component:vue-class-component 是一个 Class Decorator,也就是类的装饰器;
  • vue-property-decorator:vue-property-decorator 是基于 vue 组织里 vue-class-component 所做的拓展 import { Vue, Component, Inject, Provide, Prop, Model, Watch, Emit, Mixins } from 'vue-property-decorator';
  • vuex-class:操作 vuex 的装饰器 import { State, Getter, Action, Mutation, namespace } from 'vuex-class'

componnet 组件声明

创建组件的方式:

import { Component, Vue } from 'vue-property-decorator'

@Component
export default class Home extends Vue {

}

使用引用UI组件时:

import { Component, Vue  } from 'vue-property-decorator'
import MyList from '../components/MyList.vue'

@Component({
  components: { MyList }
})
export default class Home extends Vue {

}

data 数据

import { Component, Vue } from 'vue-property-decorator'

@Component
export default class Home extends Vue {
  private message = 'this is a string'
  private list = [1, 2, 3, 4, 5]
  private show = true
}

Prop 声明

@Prop({ type: Boolean, default: false }) value!: boolean
@Prop({ type: Function }) event!: Function
这两种在语法上叫赋值断言,!: 表示一定存在,?:表示可能不存在。
语法:@Prop(options: (PropOptions | Constructor[] | Constructor) = {})
  • PropOptions,可以使用以下选项:type,default,required,validator
  • Constructor[],指定 prop 的可选类型
  • Constructor,例如 String,Number,Boolean 等,指定 prop 的类型

method 使用

不需要使用注解,直接申明使用即可

public increment (): void {
  this.num = this.num + 1
}

// 鼠标、键盘、输入、聚焦等事件,获取事件对象时要声明事件类型。如:
private handleMouseEvent (e: MouseEvent): void {
  console.log(e)
}

private handleInputEvent (e: InputEvent) {
  console.log(e)
}

private handleFocusEvent (e: FocusEvent) {
  console.log(e)
}

Watch 监听属性

<script lang="ts">
import { Component, Watch, Vue } from 'vue-property-decorator'

@Component
export default class Home extends Vue {
  message = 123
  list = [1, 2, 3, 4, 5]

  @Watch('message')
  onMessageChange (o: number, n: number) {
    console.log(o, n)
  }

  @Watch('list', { immediate: true })
  onListChange (o: number[], n: number[]) {
    console.log(o, n)
  }
}
</script>
语法:@Watch(path: string, options: WatchOptions = {})
  • options 可使用 immediate?:boolean 立即监听 和 deep?:boolean 深度监听

computed 计算属性

计算属性可使用 getset 方法

<script lang="ts">

import { Component, Vue } from 'vue-property-decorator'
@Component
export default class Home extends Vue {
  num = 123

  get myNum (): number {
    return this.num
  }

  set myNum (value: number) {
    this.num = value
  }
  
}
</script>

生命周期函数

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'

@Component
export default class Home extends Vue {
  beforeCreate () {
    console.log('beforeCreate')
  }
  created () {
    console.log('created')
  }
  beforeMount () {
    console.log('beforeMount')
  }
  mounted () {
    console.log('mounted')
  }
  beforeUpdate () {
    console.log('beforeUpdate')
  }
  updated () {
    console.log('updated')
  }
  beforeDestroy () {
    console.log('beforeMount')
  }
  destroyed () {
    console.log('destroyed')
  }
}
</script>

Emit 事件

<script lang="ts">
import { Component, Vue, Emit } from 'vue-property-decorator'

@Component
export default class Home extends Vue {
  num = 0

  @Emit()
  imcrement (n: number) {
    this.num += n
  }

  @Emit('reset')
  resetNum () {
    this.num = 0
  }

  @Emit()
  returnValue () {
    return 123
  }

  @Emit()
  handleInputChange (e: InputEvent) {
    const target = e.target as HTMLInputElement
    return target.value
  }

  @Emit()
  promise () {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve(123)
      }, 1000)
    })
  }
}
</script>

以上 ts 写法转译为 js 写法,如下:

export default {
  data() {
    return {
      num: 0
    }
  },
  methods: {
    increment (n) {
      this.num += n
      this.$emit('increment', n)
    }

    resetNum () {
      this.num = 0
      this.$emit('reset')
    }

    returnValue () {
      this.$emit('return-value', 123)
    }

    promise () {
      const promise = new Promise((resolve, reject) => {
        setTimeout(() => {
           resolve(123)
        }, 1000)
      })

      promise .then(res => {
        this.$emit('promise', res)
      })
    }
  }
}
语法: @Emit(event?: string)
  • Emit 装饰器接收一个可选参数,该参数是 Emit 第一个参数,充当参数名。若无,Emit 会将回调函数名的 camelCase 转为 kebab-case,并将其作为事件名;
  • Emit 会将回调函数的返回值作为第二个参数,如果返回值是一个 Promise 对象,$emit 会在 Promise 对象被标记为 resolved 之后触发;
  • Emit 的回调函数的参数,会放在其返回值之后,一起被 $emit 当做参数使用。

Mixins 混入

// mixins/user.ts

import { Component, Vue } from 'vue-property-decorator'

@Component
export default class User extends Vue {
  created () {
    console.log('mixins')
  }

  mixinMethod () {
    console.log('mixinMethod')
  }
}

// Home.vue

<script lang="ts">
import { Component, Mixins } from 'vue-property-decorator'
import User from '@/mixins/user'

@Component
export default class Home extends Mixins(User) {
  
}
</script>

vuex

// store/index.ts

import Vue from 'vue'
import Vuex from 'vuex'
import user from './user'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    user
  }
})

// store/user.ts

import { MutationTree, ActionTree, Commit } from 'vuex'

interface State {
  count: number;
  str: string;
}

const state: State = {
  count: 0,
  str: 'string'
}

// eslint-disable-next-line
const mutations: MutationTree<any> = {
  increment (state: State, payload: number) {
    state.count += payload
  }
}

// eslint-disable-next-line
const actions: ActionTree<string, any> = {
  increment (context: { commit: Commit }, payload: number) {
    context.commit('increment', payload)
  }
}

export default {
  namespaced: true, 
  state,
  mutations,
  actions
}

在 vue 组件使用 vuex 数据
namespaced 为 false 的时候,state,mutations,actions 全局可以调用,为 true,生成作用域,引用时要声明模块名称。如为 namespaced: false 时:

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { State, Action } from 'vuex-class'

@Component
export default class Home extends Vue {

  @State(state => state.user.count) count!: number
  @Action('increment') increment!: Function

}
</script>

namespacedtrue

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { namespace } from 'vuex-class'
const userModule = namespace('user')

@Component
export default class Home extends Vue {

  @userModule.State(state => state.count) count!: number
  @userModule.Action('increment') increment!: Function

  // 或者
  @userModule.State
  str!: string
  @userModule.Action
  increment!: (value: number) => void

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

推荐阅读更多精彩内容