1. 将Money组件由JS改为TS
@Component里添加components
<script lang="ts">
import Vue from 'vue';
import NumberPad from '@/components/Money/NumberPad.vue';
import Types from '@/components/Money/Types.vue';
import Notes from '@/components/Money/Notes.vue';
import Tags from '@/components/Money/Tags.vue';
import {Component} from 'vue-property-decorator';
@Component({
components: {Tags, Notes, Types, NumberPad}
})
export default class Money extends Vue {
tags = ['衣', '食', '住', '行', '彩票'];
}
</script>
2. 获取Tag组件的选中的标签
Tag组件
<script lang='ts'>
// ...
toggle(tag: string) {
const index = this.selectedTags.indexOf(tag);
if (index >= 0) {
this.selectedTags.splice(index);
} else {
this.selectedTags.push(tag);
}
this.$emit('update:value', this.selectedTags);
}
// ...
</script>
Money组件
<template>
<Layout class-prefix="layout">
<NumberPad/>
<Types/>
<Notes/>
<Tags :data-source.sync="tags" @update:value="onUpdateTags"/>
</Layout>
</template>
<script lang="ts">
// ...
@Component({
components: {Tags, Notes, Types, NumberPad}
})
export default class Money extends Vue {
tags = ['衣', '食', '住', '行', '彩票'];
// vue会自动把自定义事件的值作为第一个参数传给监听事件的method
onUpdateTags(value:string){
console.log(value);
}
}
</script>
3. 获取Note组件的Notes
使用@Watch监听value的变化
<script lang="ts">
import Vue from 'vue'
import {Component, Watch} from 'vue-property-decorator';
@Component
export default class Notes extends Vue{
value = ''
@Watch('value')
onValueChanged(value:string, oldValue:string){
this.$emit('update:value', value)
}
}
</script>
Money组件监听事件
<template>
<Layout class-prefix="layout">
<NumberPad/>
<Types/>
<Notes @update:value="onUpdateNotes"/>
<Tags :data-source.sync="tags" @update:value="onUpdateTags"/>
</Layout>
</template>
<script lang="ts">
// ...
onUpdateNotes(value:string){
console.log(value);
}
}
</script>
4. 获取Type组件的type
<script lang="ts">
//...
@Watch('type')
onTypeChanged(value:string){
this.$emit('update:value', value)
}
}
</script>
5. 获取NumberPad组件的值
<script lang="ts">
// ...
ok() {
this.$emit('update:value', this.output)
}
}
</script>
6. 将数据收集到一起
声明Record类型
type Record = {
tags: string[],
notes: string,
type: string,
amount: number,
createAt?: Date
}
record:Record = {
tags: [], notes: '', type:'-', amount: 0
}
7. 存储到LocalStorage
record需要深拷贝,否则每条数据都一样
saveRecord(){
const record2:Record = JSON.parse(JSON.stringify(this.record))
record2.createAt = new Date()
this.recordList.push(record2)
}
@Watch('recordList')
onRecordListChanged(){
window.localStorage.setItem('recordList', JSON.stringify(this.recordList))
}
程序加载时就读取localStorage
recordList:Record[] = JSON.parse(window.localStorage.getItem('recordList') || '[]')