Vue CLI 内置了 TypeScript 工具支持。在 Vue 的下一个大版本 (3.x) 中也计划了相当多的 TypeScript 支持改进,包括内置的基于 class 的组件 API 和 TSX 的支持。
- 创建工程
npm install --global @vue/cli
vue create my-project-name:选择 "Manually select features (手动选择特性)" 选项 - 注意5点
-
methods
可以直接声明为类成员方法。<script lang="ts"> import { Component, Prop, Vue } from 'vue-property-decorator'; @Component({ props:{ msg: String } }) export default class HelloWorld extends Vue { // @Prop() private msg!: string; // method greet () { alert('greeting: ' + this.msg) } } </script>
-
可以将计算属性声明为类属性访问器。
<script lang="ts"> import { Component, Prop, Vue } from 'vue-property-decorator'; @Component export default class HelloWorld extends Vue { // @Prop() private msg!: string; // computed get computedMsg () { return 'computed ' + this.msg } } </script>
-
Initial
data
可以声明为类属性(如果使用Babel,则需要babel-plugin-transform-class-properties)。<script lang="ts"> import { Component, Prop, Vue } from 'vue-property-decorator'; @Component export default class HelloWorld extends Vue { // @Prop() private msg!: string; // initial data msg = 123 } </script>
-
data
,render
并且所有Vue生命周期钩子也可以直接声明为类成员方法,但是您不能在实例本身上调用它们。声明自定义方法时,应避免使用这些保留名称。 -
对于所有其他选项,将它们传递给装饰器函数。
-