English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Detailed Explanation of the Use of localStorage and sessionStorage in Vue

1. Several problems exposed in project use

Everyone uses the native syntax directly, such as localStorage['aaa'] = 'This is a sample string', which has a high degree of coupling. If one day we need to change the implementation method or control the storage size, a lot of code needs to be modified

In large projects, the names of keys taken by everyone are likely to be repeated, and this will also cause global pollution

Due to the irregular use of localStorage, storage space waste and insufficient space have occurred

2. Solutions

Encapsulate the usage methods of storage, process them uniformly

Standardize the naming rules of storage keys
Standardize the usage of storage

2.1. Encapsulate unified methods

Encapsulating into methods can reduce coupling, facilitate the switch of implementation methods, and control the size of storage

Different implementations can be achieved by configuring different parameters

Edit the project structure as shown in the figure

Code Implementation

/*
 * storage.js
 */
/*
 * @Author: 石国庆
 * @Desc: Encapsulation of local data storage methods
 * @Date: 2017.11.14
 * @Ref:
 *  https://github.com/WQTeam/web-storage-cache
 *  https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage
 * @Explain:To avoid creating new objects, it is necessary to write a few more times
 * @Example:
 *
 * 1、LocalStorage的使用
 * import storage from '@/utils/storage.js'
 * storage.setItem('shiguoqing0',[1,2,3,4,5,6])
 * storage.setItem('shiguoqing1},{userId:'dfdf',token:11232323)
 * storage.setItem('shiguoqing2','dfdfdf')
 * console.log(storage.getItem('shiguoqing0'))
 * console.log(storage.getItem('shiguoqing1))
 * console.log(storage.getItem('shiguoqing2))
 * storage.removeItem('shiguoqing2')
 *
 *
 * 2Usage of SessionStorage
 * storage.setItem('shiguoqing0',[1,2,3,4,5,6],{type:'session'})
 *
 * */
// TODO: Implement other methods
// TODO: Set timeout for the configuration
/*
 * method implementation
 * */
import local from './storage/localstorage.js'
import session from './storage/session.js'
import cookies from './storage/cookies.js'
import json from './storage/json.js'
/*
* function body
* */
let storage= {
 config:{
  type:'local',// local,session,cookies,json
  expires:new Date().getTime() + 100 * 24 * 60 * 60 * 1000
 },
 getStorage(options){
  let config={}
  if(options){
   config=Object.assign({},this.config,options)
  }else{
   config=this.config
  }
  return this.createStorage(config.type)
 },
 createStorage(name){
  switch(name){
   case 'local':return local;break
   case 'session':return session;break
   case 'cookies':return cookies;break
   case 'json':return json;break
  }
 },
 getItem(key,options){
  let store = this.getStorage(options)
  return store.getItem(key)
 },
 setItem(key, value,options){
  let store = this.getStorage(options)
  store.setItem(key,value)
 },
 removeItem(key,options){
  let store = this.getStorage(options)
  store.removeItem(key)
 },
 getAll(){},
 clear(options){
  let store = this.getStorage(options)
  store.clear()
 },
 key(n){},
 lenght(){},
 has(key){},
 forEach(cb){},
 deleteAllExpires(){},
 // Obtain the maximum storage space: this method can only be used with LocalStorage and SessionStorage
 getMaxSpace(options){
  let store = this.getStorage(options)
  store.getMaxSpace()
 },
 // Get the used space: This method can only be used by LocalStorage and SessionStorage
 getUsedSpace(options){
  let store = this.getStorage(options)
  store.getUsedSpace()
 }
}
export default storage
// https://segmentfault.com/a/1190000002458488
// 5to iterate over the keys stored in localStorage
//  .length total data volume, for example: localStorage.length
//  .key(index) to get the key, for example: var key = localStorage.key(index);
// Note: The data stored in localStorage cannot be shared across browsers, each browser can only read its own data, storage space5M.
// Timeout settings
// function(st, key, value, expires) {
//  if (st == 'l') {
//   st = window.localStorage;
//   expires = expires || 60;
//  } else {
//   st = window.sessionStorage;
//   expires = expires || 5;
//  }
//  if (typeof value != 'undefined') {
//   try {
//    return st.setItem(key, JSON.stringify({
//     data: value,
//     expires: new Date().getTime() + expires * 1000 * 60
//    });
//   }
//  } else {
//   var result = JSON.parse(st.getItem(key) || '{}');
//   if (result && new Date().getTime() < result.expires) {
//    return result.data;
//   } else {
//    st.removeItem(key);
//    return null;
//   }
//  }
// }
/*
 * localstorage.js
 * Implementation of localstorage
 */
// This is a bit strange, the file name is local.js and it cannot be parsed as a js file
export default {
 getItem(key){
  let item = localStorage.getItem(key)
  // This needs to determine whether it is a string or an object
  let result = /^[{\[].*[}\]]$/g.test(item)
  if (result) {
   return JSON.parse(item)
  } else {
   return item
  }
 },
 setItem(key, value){
  // This needs to determine whether it is a string or an object
  if (typeof value == "string") {
   localStorage.setItem(key, value)
  } else {
   let item = JSON.stringify(value)
   localStorage.setItem(key, item)
  }
 },
 removeItem(key){
  localStorage.removeItem(key)
 },
 getAll(){},
 clear(){
  localStorage.clear()
 },
 key(n){},
 forEach(cb){},
 has(key){},
 deleteAllExpires(){},
 // Get the maximum storage capacity of localstorage
 getMaxSpace(){
  if (!window.localStorage) {
   console.log('The current browser does not support localStorage!')
  }
  var test = '0'123456789'''
  var add = function (num) {
   num += num
   if (num.length == 10240) {
    test = num
    return
   }
   add(num)
  }
  add(test)
  var sum = test
  var show = setInterval(function () {
   sum += test
   try {
    window.localStorage.removeItem('test')
    window.localStorage.setItem('test', sum)
    console.log(sum.length / 1024 + 'KB')
   }
    console.log(sum.length / 1024 + 'KB exceeds the maximum limit')
    clearInterval(show)
   }
  }, 0.1)
 },
 // Get the used space of localstorage
 getUsedSpace(){
  if (!window.localStorage) {
   console.log('The browser does not support localStorage')
  }
  var size = 0
  for (item in window.localStorage) {
   if (window.localStorage.hasOwnProperty(item)) {
    size += window.localStorage.getItem(item).length
   }
  }
  console.log('The current usage capacity of localStorage is ' +  / 1024).toFixed(2) + 'KB')
 }
}
/*
 * session.js
 * The implementation of sessionstorage
 */
export default {
 getItem(key){
  let item = sessionStorage.getItem(key)
  // This needs to determine whether it is a string or an object
  let result = /^[{\[].*[}\]]$/g.test(item)
  if (result) {
   return JSON.parse(item)
  } else {
   return item
  }
 },
 setItem(key, value){
  // This needs to determine whether it is a string or an object
  if (typeof value == "string") {
   sessionStorage.setItem(key, value)
  } else {
   let item = JSON.stringify(value)
   sessionStorage.setItem(key, item)
  }
 },
 removeItem(key){
  sessionStorage.removeItem(key)
 },
 getAll(){},
 clear(){
  sessionStorage.clear()
 },
 key(n){},
 forEach(cb){},
 has(key){},
 deleteAllExpires(){},
 // Get the maximum storage capacity of localstorage
 getMaxSpace(){
  if (!window.sessionStorage) {
   console.log('The current browser does not support sessionStorage!')
  }
  var test = '0'123456789'''
  var add = function (num) {
   num += num
   if (num.length == 10240) {
    test = num
    return
   }
   add(num)
  }
  add(test)
  var sum = test
  var show = setInterval(function () {
   sum += test
   try {
    window.sessionStorage.removeItem('test')
    window.sessionStorage.setItem('test', sum)
    console.log(sum.length / 1024 + 'KB')
   }
    console.log(sum.length / 1024 + 'KB exceeds the maximum limit')
    clearInterval(show)
   }
  }, 0.1)
 },
 // Get the used space of localstorage
 getUsedSpace(){
  if (!window.sessionStorage) {
   console.log('Browser does not support sessionStorage')
  }
  var size = 0
  for (item in window.sessionStorage) {
   if (window.sessionStorage.hasOwnProperty(item)) {
    size +
   }
  }
  console.log('The current sessionStorage usage capacity is ' +  / 1024).toFixed(2) + 'KB')
 }
}
/*
 * cookies.js
 * The implementation of cooikes, it is estimated that there will not be time to implement it in this lifetime
 */
export default {
 getItem(key){},
 setItem(key, value){},
 removeItem(key){},
 getAll(){},
 clear(){},
 key(n){},
 forEach(cb){},
 has(key){},
 deleteAllExpires(){}
}
/*
 * json.js
 * The implementation of json, it is estimated that there will not be time to implement it in this lifetime
 */
export default {
 getItem(key){},
 setItem(key, value){},
 removeItem(key){},
 getAll(){},
 clear(){},
 key(n){},
 forEach(cb){},
 has(key){},
 deleteAllExpires(){}
}

2.2. Standardize the use of namespaces

To prevent key value pollution, we can use namespaces reasonably

We can define namespaces, but we cannot store a lot of data in the same object, as the operation amount will be too large later on

For example, placing the global ones under global

For example, adding system prefixes to each functional system

The naming convention of a system's namespace should be designed in advance, otherwise, many people will not follow the rules when the actual development starts

Items used globally should be reflected in the README.md document

Example

* localStorage['SGQ.global.userAuthor']: Information of the user logged in is all here, including menu, organization, and group
* localStorage['SGQ.global.systemName']: Name of the system logged in
* localStorage['SGQ.vuex.state']: Storage address of the state in vuex, which contains all items
* localStorage['SGQ.wms.warehouse']: Information of the warehouse needed by wms
+ localStorage['SGQ.wms.warehouse'].permissionId
+ localStorage['SGQ.wms.warehouse'].dataResource
* localStorage['SGQ.tms.org']: Information of the outlets needed by tms
+ localStorage['SGQ.tms.org'].permissionId
+ localStorage['SGQ.tms.org'].orgName

2.3. storage usage specifications

2.3.1. Reason for the problem

The reason for this problem is that we need to do permission login, and during the login, it always reported that there is not enough storage space. After investigating the cause, it was found that the backend returned all the thousands of data of super administrators, which was not enough. Later, the problem was solved by modifying the data content returned by the backend interface.

But what thoughts do we gain from this incident?

The storage capacity of localStorage and sessionStorage is basically the same across different browsers5M

The storage of localStorage and sessionStorage follows the domain

The localStorage storage under boss.hivescm.com is5M

b2The localStorage storage under b.hivescm.com is also5M

Even though this problem is solved this time, we should establish a set of plans to make full use of the common storage of localStorage and sessionStorage under a single domain10M space

2.3.2. storage usage plan

Items used globally, shared items, and items stored permanently are stored in localStorage

Items that do not require permanent storage should be cleared in time after use

If the data volume is too large, do not store it locally, and become dynamic acquisition

Indexeddb with a larger storage capacity can be used, but there are compatibility issues

Character limit can be set for the things to be stored in storage in the implementation plan

Fully and reasonably utilize the H of sessionStorage and localStorage5Characteristics

For example: list data is stored in vuex and will also be stored in localStorage

For example: some data of form validation are stored in sessionStorage

3. Other

3.1. Extension and expansion

From this, it can be generalized to event handling, and unnecessary events should be cleaned up in time when exiting the vue component

For example: this.bus.$on('aa') should use this.bus.$off('aa') to unload the event

3.2. Character length acquisition

var len = 0
for (var i = 0; i < val.length; i++) {
 if (val[i].match(/[^\x00-\xff]/ig) != null) //Full-width
  len += 2 //If it is full-width, it occupies two bytes, if a field in mysql is text, if the encoding is set to utf-8, then a Chinese character occupies3bytes, gbk is two bytes
 else
  len += 1 //Half-width occupies one byte
}
return len

That's all the content I have sorted out about the usage of localStorage and sessionStorage in Vue, thank you for your support of the yell tutorial.

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (When reporting via email, please replace # with @) to report violations, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.

You May Also Like