localStorage
numberPad点OK时,抛出一个事件,让父组件监听
this.$emit('submit', Number(this.output));
父组件定义一个recordList来存储record, 类型为Record[]
recordList: Record[] = [];
将record push进数组时,应当先对record进行深拷贝,不然每次push都传的是record的地址
saveRecord(){
// 深拷贝,先转换成JSON,再转换为对象
const record2 = JSON.parse(JSON.stringify(this.record));
this.recordList.push(record2);
}
@watch recordList,有变化时存入localStorage
@Watch('recordList')
onRecordListChanged(){
window.localStorage.setItem('records', JSON.stringify(this.recordList))
}
为了刷新后数据不丢失,初始化时应当读取localStorage
recordList: Record[] = JSON.parse(window.localStorage.getItem('records') || '[]');
存储时间
typescript类型除了js的数据类型,还可以是类(构造函数)
type Record = {
...
createTime?: Date; // 类
}
saveRecord(){
...
record2.createTime = new Date();
...
}
数据迁移
const version = window.localStorage.getItem('version') || '0';
const recordList: Record[] = JSON.parse(window.localStorage.getItem('records') || '[]');
if(version === '0.0.1'){
recordList.forEach(record=>{
record.createTime = new Date(2020, 0, 1);
});
window.localStorage.setItem('records', JSON.stringify('recordList'));
}
window.localStorage.setItem('version', '0.0.2');
版本升级应当按版本升级次序