typescript 对 vue 2.x 的支持不是很好,但我们还是有必要学习一下。
本文会列出 vue 中常用功能在 typescript 里的写法。
基于类的组件
单页面是以类的形式使用的,所以用 typescript 定义 vue 应使用下面的语法
- 在
script里添加lang='ts' - 在
Component里定义组件的name
1 | <script lang="ts"> |
javascript 的代码代码如下:
1 | <script> |
引入其他组件
- 使用
import引入其他组件 - 在
Component.components里添加引入的组件 - 在
html模板里使用组件
1 | <template> |
基础属性
data
- 直接定义即可。
1 |
|
prop
- 使用
import引入Prop - 在
@Prop装饰器中添加其他属性
1 | import { Component, Prop, Vue } from 'vue-property-decorator' |
Computed
- 直接使用
get返回 - 使用
set+get定义可修改的computed
1 | export default class HelloTs extends Vue { |
Methods
- 直接定义
1 | import { Component, Vue } from 'vue-property-decorator' |
Watchers
Watch的用法和Javascript中的handler语法类似- 使用
import导入Watch - 在
Watch装饰器中添加监听对象和其他属性 - 添加
handler方法
1 | import { Component, Watch, Vue } from 'vue-property-decorator' |
Emit
- 父组件接受
Emit的参数为子组件return的值+Emit函数自身的参数 - 使用
import导入Emit - 在
Emit装饰器中添加this.$emit('xxx')的方法,如未添加,使用下面定义的函数A(用-分隔) - 执行完函数
A后会自动调用this.$emit('A',params)方法 - 在父组件调用
Emit
1 | // ./HelloTs.vue: 子组件 |
1 | // ./Father.vue: 父组件 |
生命周期钩子
- 直接使用
1 | import { Component, Vue } from 'vue-property-decorator' |
Mixins
Mixins文件extends Vue- 引入文件
extends Mixins
编写Mixins
- 新建
mixin文件夹 - 新建
ProjectMixin.ts文件, - 添加文件内容,和
.vue中的<script>标签内一样
1 | // @/mixin/ProjectMixin.ts |
引入Mixins
- 使用
import引入Mixins - 引入
Mixins文件ProjectMixin.ts - 修改继承
extends Vue为extends Mixins(ProjectMixin) - 调用
ProjectMixin.ts中的变量和方法
1 | // @/components/HelloTs.vue |
Vuex
- 在
typescript中使用Vuex需要引入2个包vuex-module-decorators和vuex-class
编写Vuex
- 在
store文件夹下新建modules文件夹 - 在
modules文件夹下新建user.ts文件 user.ts文件添加内容store.index.ts内引入user
1 | // @/store/modules/user.ts |
1 | // @/store/index.ts |
使用Vuex
- 引入
vuex-class中的namespace - 定义
modules常量 - 定义及调用
Vuex
1 | // @/components/HelloTs.vue |