Add.vue的封装

  1. Add.vue的组件
1
2
3
4
5
6
7
8
@Component({
  components: {
    Scroll,
    TabBar,
    NumberPad,
    TagTable
  }
})
  1. 在Add.vue中获取tagList,经过详细考虑我发现使用计算属性和watch能更好的获取tagList和当前选择标签的id
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
export default class Add extends Vue {
  selectedId: number = 0;
  type: string = "-";
  buttonSelected: boolean = false;

  get tagList() {
    if (this.type === "-") {
      return this.$store.state.tagList;
    } else if (this.type === "+") {
      return expendList;
    }
  }

  @Watch("tagList")
  onTagListChanged(newVal: Tag) {
    this.selectedId = this.tagList[0] ? this.tagList[0].id : 0;
  }
  1. 封装一个TagTable.vue组件根据传过来的TagList
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<template>
  <div class="tag-list">
    <header>{{tagList[0].name}}</header>
    <ul class="icons">
      <li v-for="tag in tagList" :key="tag.id">
        <Icon
          class="icon"
          :name="tag.name"
          :class="{'selected':selectedTag.id===tag.id}"
        />
        <span>{{tag.name}}</span>
      </li>
    </ul>
  </div>
</template>

<script lang='ts'>
import Vue from "vue";
import { Component, Prop } from "vue-property-decorator";

@Component
export default class TagList extends Vue {
  @Prop() readonly tagList!: Tag[];
}
  1. 封装NumberPad来记录金额和备注
  • 点加ok时进行数组操作 来进行加法运算
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
 ok() {
    const addArray = this.output.split("+");
    this.output = "0";
    for (let i = 0; i < addArray.length; i++) {
      if (addArray[i] === "") return;
      this.output = (
        parseFloat(this.output) + parseFloat(addArray[i])
      ).toString();
    }

    this.$emit("createRecord", this.output, this.notes);
    this.notes = "";
    this.output = "0";
  }

数据记录

  1. 在Add.vue中使用record数组来存储每次添加的记录
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
  record: RecordItem = {
    tag: {},
    notes: "",
    type: "-",
    amount: 0
  };
  
  type RecordItem = {
  tag: Tag | {};
  notes: string;
  type: string;
  amount: number;
  createdAt?: string;
}
  1. 在store里面封装recordList的方法
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
    // recordList方法
    fetchRecords(state) {
      state.recordList = JSON.parse(window.localStorage.getItem('recordList') || '[]') as RecordItem[];
    },
    createRecord(state, record) {
      const record2: RecordItem = clone(record);
      record2.createdAt = new Date().toISOString();
      state.recordList.push(record2);
      store.commit('saveRecords')
    },
    saveRecords(state) {
      window.localStorage.setItem('recordList', JSON.stringify(state.recordList));
    },