# 实现Money Types 功能

<template>
  <div>
    <ul class="types">
      <li :class="type === '-' && 'selected'" @click="selectType('-')">支出</li>
      <li :class="type === '+' && 'selected'" @click="selectType('+')">收入</li>
    </ul>
  </div>
</template>

# JS 实现

<script>
  export default {
    name: 'Types',
    data(){
      return {
        type: '-'
      }
    },
    methods:{
      selectType(type){
        if(type !== '-' && type !== '+'){
          throw new Error('type is unknown')
        }
        this.type = type
      }
    }
  }
</script>

# TS 实现

<script lang="ts">
   import Vue from 'vue'
   import {Component, Prop} from 'vue-property-decorator';
    @Component
    export default class Types extends Vue{
      type = '-';
      @Prop(Number) xxx: number | undefined;
      // Prop 告诉 Vue  xxx 不是 data  是 prop
      // Number 告诉 Vue  xxx 运行时是 Number
      //  xxx 属性名
      //  number | undefined 告诉 TS xxx 编译时类型
      selectType(type: string){
        if(type !== '-' && type !== '+'){
          throw new Error('type is unknown')
        }
        this.type = type
      }
      mounted(){
        if(this.xxx === undefined){
          console.log('undefined');
        }else{
          console.log(this.xxx.toString());
          console.log(this.xxx.yyy);
        }        
        //为什么 this.xxx.yyy.zzz 会报错:
        // xxx可能为undefined,yyy属性不存在
      }
    }
</script>
# TS知识补充

TypeScript 好处

  1. 类型提示:更智能的提示
  2. 编译时报错:还没运行代码就知道自己写错了
  3. 类型检查:无法点出错误的属性

vue-property-decorator 库 来自 https://github.com/kaorun343/vue-property-decorator

@Component //装饰器 来自 https://class-component.vuejs.org/

必写项

import Vue from 'vue'
import Component from 'vue-class-component'

@Component
export default class HelloWorld extends Vue {}

data 用法

<template>
  <div>{{ message }}</div>
</template>

<script lang="ts">
  import Vue from 'vue'
  import Component from 'vue-class-component'

  @Component
  export default class HelloWorld extends Vue {
    // Declared as component data
    message = 'Hello World!'
  }
</script>

methods 用法

<template>
  <button v-on:click="hello">Click</button>
</template>

<script lang="ts">
  import Vue from 'vue'
  import Component from 'vue-class-component'

  @Component
  export default class HelloWorld extends Vue {
    // Declared as component method
    hello() {
      console.log('Hello World!')
    }
  }
</script>

# 写Vue组件的三种方式(单文件组件)

1.用JS对象

export default { data, props, methods, created, ...}

2.用 TS 类

<script lang="ts">
   import Vue from 'vue'
   import {Component} from 'vue-property-decorator';
   @Component
   export default class XXX extends Vue{
     xxx: string = 'hi';
     @Prop(Number) xxx: number|undefined;  
}
</script>

3.用JS类

<script lang="js">
   import Vue from 'vue'
   import {Component} from 'vue-property-decorator';
   @Component
   export default class XXX extends Vue{
     xxx = 'hi';
}
</script>