下面给大家提供了一个实例完整的ts示例:
- 包含前面讲到的所有实例选项,以及router导航守卫周期、vuex使用等
- 包含各个选项、属性的顺序排列。结合了部分官方的推荐 Vue 风格指南 - 组件/实例的选项的顺序
- 包含各属性的public、private等修饰符的使用
这里例子比较简单,仅是为了展示大部分的属性,若要更细致的了解各实例选项的写法,可以参考前面的文章。
// TodoApp.vue
<template>
<div class="todo-app">
<div ref="refTitle">
this is title {{ UserModule.allName }} - {{ userAge }}
</div>
<TodoItem ref="refTodoItem" />
</div>
</template>
<script lang="ts">
import { Component, Mixins, Prop, Emit, Watch, Provide, Inject, Ref } from 'vue-property-decorator'
import { Route, NavigationGuardNext } from 'vue-router'
import TodoItem from '@/components/TodoItem.vue'
import colorDirective from '@/directive/colorDirective'
import FormMixins from '@/mixins/FormMixins'
import UserMixins from '@/mixins/UserMixins'
import { UserModule } from '@/store/modules/user'
type gender = '男' | '女'
@Component({
components: { TodoItem },
directives: {
color: colorDirective,
},
filters: {
formatUserName(val: string) {
return `姓名:${val}`
},
},
})
export default class TodoApp extends Mixins(FormMixins, UserMixins) {
// ref
@Ref('refTitle') readonly refTitle!: HTMLDivElement // DOM
@Ref('refTodoItem') readonly refTodoItem!: TodoItem // Vue Component
// provide
@Provide('department') public department = '销售部'
// inject
@Inject('userId') public injectUserId = 1
// Model
@Model('user-age')
readonly userAge!: number
// prop
@Prop({ type: [String, Number], default: '' })
readonly userId!: string | number
// emit
@Emit('user-age')
public emitAgeChange(age: number) {
return age
}
@Emit('add-to-count')
public emitAddToCount(val: number) {
return val
}
// Vuex store module
public readonly UserModule = UserModule
// data
public userName: string = '韩梅梅'
public gender: gender = '女'
// computed
public get userInfo(): string {
return `性别:${this.gender},姓名:${this.userInfo}`
}
// watch
@Watch('gender', { immediate: true, deep: true })
private onGenderChange(newVal: gender, oldVal: gender) {
console.log('新:', newVal)
console.log('旧:', oldVal)
}
// Hook: 生命周期
private mounted() {
console.log('mounted')
}
private beforeDestroy() {
console.log('beforeDestroy')
}
// Hook: 导航守卫
private beforeRouteEnter(_to: Route, _from: Route, next: NavigationGuardNext) {
next()
}
private beforeRouteLeave(_to: Route, _from: Route, next: NavigationGuardNext) {
next()
}
// methods
public changeUserGender(gender: gender) {
this.gender = gender
}
}
</script>