5记账 Vue 项目-Money.vue 组件(下)

185 阅读2分钟

5.1 JS组件


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


<script lang="js">


export default {
  name:'Types',
  data(){
  return {
     type:'-'//- 表示支出 ,+表示收入
    }
  },
  methods:{//自由切换收入和支出
   selectType(type){ // type只能是- 和+ 其中一个
   if(type !== '-' && type !=='+'){
    throw new Error('type is number')
   }
     this.type = type
    }
  }
  
}
</script>



5.2 TS组件

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


<script lang="ts">
import Vue from "vue";
import { Component, Prop } from "vue-property-decorator";
@Component
export default class Types extends Vue {
  type = "-"; // '-'表示支出,'+'表示收入
  selectType(type: string) {
    if (type !== "-" && type !== "+") {
      throw new Error("type is unknown");
    }
    this.type = type;
  }
}
</script>

5.3 TS组件@Prop装饰器

TS的好处:

-   类型提示:更智能的提示
-   编译时报错:还没运行代码就知道自己写错了
-   类型检查:无法点出错误的属性
查看包的最新版本

npm info typescript version

查看当前安装的包的版本

npm ls typescirpt
# 或
yarn list typescript



安装好之后需要File->invalidate Caches/...

使用第三方vue-property-decorator来使用ts的prop

  //Prop 告诉 Vue, xxx不是 data 是 prop
  //Number 告诉 Vue, xxx 运行时, 是个Number
  //xxx 属性名
  //number | undefined 告诉 TS xxx 的编译时的类型
@Prop(Number) xxx: number | undefined

image.png

5.4 TS的本质

image.png

5.5 Vue单文件的写法

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

  • 用JS对象:
export default { data, props, methods, created, ...}
  • 用 TS 类
@Component export default class XXX extends Vue{ xxx: string = 'hi'; @Prop(Number) xxx: number|undefined; }
  • 用 JS 类
@Component export default class XXX extends Vue{ xxx = 'hi' }

5.6 numberPad 模块

数字键盘逻辑:\
1 当前为0\
直接输入0-9需要把0变为对应的数\
当时`.`时,需要追加成`0.`

2不能出现两个`.`

删除逻辑:\
1 利用字符串`slice`来删除最后一个\
2 `output`只有1位时, `output`变为`0`

5.7 notes 模块 - v-model

使用v-model 代替 :value ,@input

v-model='value'
等于
:value="value" @input="value = $event.target.value"

5.8 tags 模块

`...`展开运算符, 扩展运算符

5.9 @Prop

@Prop(Boolean) xxx!: boolean; 

不能直接`操作`外部数据\
eg`Tags.vue`中的`dataSource`, 应该传给`Money.vue`修改

为什么呢?原因是这样的:

  1. 左边的 Boolean 是跟 Vue 说 xxx 的类型是 Boolean(运行时类型)
  2. 如果不写左边的 Boolean,那么 Vue 就不知道 xxx 的类型是什么了,默认就把 xxx 当作字符串了
  3. 因此,当你给 xxx 传值时,Vue 会将其自动转换成字符串。而与我们的预期「xxx 是 boolean」不相符,这就是 bug。

等你遇到 prop 类型错误的时候,你就会想起我说的这番话了,目前你就看一眼这篇文章就行了。