background

During mobile terminal development, some data on page A needs to be transferred to page B for creation. As the page is different, the data on page A will be cleared when page B is returned to page A. In this case, the data on page A needs to be temporarily saved.

Implementation scheme

The options for staging data include in-memory, Cookie, localStorage, SessionStorage, and IndexDB. The solution I chose, regardless of the location, is to store the data as the page leaves, and read and clean the data as the page enters.

It is suitable for data that needs to be stored temporarily before leaving and needs to be read when returning.

Store the data

Define the data store logic.

setStorageData() {
  localStorage.setItem(LAST_DATA, JSON.stringify(this.detail))
  this.$store.commit('saveList'.JSON.parse(JSON.stringify(this.detailList)))
}
Copy the code

Data is stored before the jump

jumpToEditDetail() {
  this.setStorageData();
  this.$router.push({
    path: `/newPath`
  });
}
Copy the code

Return to page load and clear data

mounted() {
  const isBack = this.readAndClearStorage();
  if (isBack) {
    this.getDetailSrcUrl();
    return;
  }
  this.getDraftDetail();
}

readAndClearStorage() {
  const str = localStorage.getItem(LAST_DATA);
  const lastData = JSON.parse(str)
  let isBack = false;
  if(str ! = ='{}') {
    this.detail = lastData;
    isBack = true;
  } else {
    this.detail = this.getDefaultDetail();
  }
  localStorage.setItem(LAST_DATA, '{}')

  this.detailList = JSON.parse(JSON.stringify(this.newList))
  this.$store.commit('saveList'[]),return isBack;
}
Copy the code

conclusion

The idea is to store, read, and clean up the data in a single component, and the target page doesn’t need to worry about the related logic.

Data that needs to be read by the entire system should be stored in the memory when the entire system is initialized. Data is read from the memory to prevent the system from being flooded with storage-related codes.