改为TS组件
type组件的JS代码
export default {name: 'Types',props:['xxx'],data(){return {type: '-' // - 表示支出 + 表示收入}},mounted() {console.log(this.xxx)},methods:{selectType(type){if(type !== '-' && type !== '+'){throw new Error(`${type} is unknown`)}this.type = type}}}
改写为TS
<script lang="ts">import Vue from 'vue'import {Component} from 'vue-property-decorator';@Componentexport default class Types extends Vue {// datatype = '-' // - 表示支出 + 表示收入// methodselectType(type: string) {if (type !== '-' && type !== '+') {throw new Error('type is unknown')}this.type = type}}</script>
必须引入Component, 官方文档 https://github.com/kaorun343/vue-property-decorator
@Prop
使用Vue Class Component的prop
官方文档:https://class-component.vuejs.org/guide/props-definition.html
import Vue from 'vue';import {Component} from 'vue-property-decorator';const GreetingProps = Vue.extend({props: {name: String}})@Componentexport default class Types extends GreetingProps {type = '-'; // - 表示支出 + 表示收入selectType(type: string) {if (type !== '-' && type !== '+') {throw new Error('type is unknown');}this.type = type;}mounted(){console.log(this.name);}}
使用Vue Property Decorator的prop
文档:https://github.com/kaorun343/vue-property-decorator#Prop
import Vue from 'vue';import {Component, Prop} from 'vue-property-decorator';@Componentexport default class Types extends Vue {@Prop(Number) readonly xxx: number | undefined// @Prop告诉Vue xxx不是data是prop// Number 告诉 Vue xxx的类型,运行时检查// number | undefined告诉 TS xxx的类型, 编译时检查type = '-'; // - 表示支出 + 表示收入selectType(type: string) {if (type !== '-' && type !== '+') {throw new Error('type is unknown');}this.type = type;}mounted(){// 当类型有undefined需要判断if (this.xxx !== undefined) {console.log(this.xxx.toString());}}}
tips: 获取TS最新版本号
npm info typescript version

