localStorage

numberPad点OK时,抛出一个事件,让父组件监听

  1. this.$emit('submit', Number(this.output));

父组件定义一个recordList来存储record, 类型为Record[]

  1. recordList: Record[] = [];

将record push进数组时,应当先对record进行深拷贝,不然每次push都传的是record的地址

  1. saveRecord(){
  2. // 深拷贝,先转换成JSON,再转换为对象
  3. const record2 = JSON.parse(JSON.stringify(this.record));
  4. this.recordList.push(record2);
  5. }

@watch recordList,有变化时存入localStorage

  1. @Watch('recordList')
  2. onRecordListChanged(){
  3. window.localStorage.setItem('records', JSON.stringify(this.recordList))
  4. }

为了刷新后数据不丢失,初始化时应当读取localStorage

  1. recordList: Record[] = JSON.parse(window.localStorage.getItem('records') || '[]');

存储时间

typescript类型除了js的数据类型,还可以是(构造函数)

  1. type Record = {
  2. ...
  3. createTime?: Date; // 类
  4. }
  5. saveRecord(){
  6. ...
  7. record2.createTime = new Date();
  8. ...
  9. }

数据迁移

  1. const version = window.localStorage.getItem('version') || '0';
  2. const recordList: Record[] = JSON.parse(window.localStorage.getItem('records') || '[]');
  3. if(version === '0.0.1'){
  4. recordList.forEach(record=>{
  5. record.createTime = new Date(2020, 0, 1);
  6. });
  7. window.localStorage.setItem('records', JSON.stringify('recordList'));
  8. }
  9. window.localStorage.setItem('version', '0.0.2');

版本升级应当按版本升级次序