构建项目
通过官方脚手架构建安装
# 如果没有安装 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 计算属性
计算属性可使用 get
、set
方法
<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>
若 namespaced
为 true
:
<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>