Encapsulation of sessionStorage

What is the difference between Cookie, localStorage and sessionStorage?

  • cookieIt is the data (usually encrypted) that the website stores on the user's local terminal (Client Side) in order to identify the user
  • The cookie data is always carried in the same-origin http request (even if it is not needed), and it will be transferred back and forth between the browser and the server
  • sessionStorageAnd localStoragewill not automatically send the data to the server, only save it locally
  • Storage size:
    • cookieData size cannot exceed 4k
    • sessionStorageAnd localStoragealthough there is also a storage size limit, the ratio is cookiemuch larger and can reach 5M or more
  • Duration:
    • localStorage Store persistent data, the data will not be lost after the browser is closed unless the data is actively deleted
    • sessionStorage Data is automatically deleted after the current browser window is closed
    • cookieThe set cookieexpiration time is always valid even if the window or browser is closed

Why do you want to encapsulate Storage? Doesn't it already have API?

  • Storage itself has API, but it is just a simple key and value form

  • Storage only stores strings and needs to be manually converted into json objects

  • Storage can only be emptied once, not individually

    // Storage封装
    const STORAGE_KEY = 'mall'
    
    export default {
          
          
      setItem (key, value, moduleName) {
          
          
        if (moduleName) {
          
          
          const val = this.getItem(moduleName)
          val[key] = value
          this.setItem(moduleName, val)
        } else {
          
          
          const val = this.getStorage()
          val[key] = value
          window.sessionStorage.setItem(STORAGE_KEY, JSON.stringify(val))
        }
      },
      // 获取某一个模块下面的属性user下面的userName
      getItem (key, moduleName) {
          
          
        if (moduleName) {
          
          
          const val = this.getItem(moduleName)
          if (val) return val[key]
        }
        return this.getStorage()[key]
      },
      getStorage () {
          
          
        return JSON.parse(window.sessionStorage.getItem(STORAGE_KEY) || {
          
          })
      },
      clear (key, moduleName) {
          
          
        const val = this.getStorage()
        if (moduleName) {
          
          
          if (val[moduleName]) return
          delete val[moduleName][key]
        } else {
          
          
          delete val[key]
        }
        window.sessionStorage.setItem(STORAGE_KEY, JSON.stringify(val))
      }
    }
    
    

Guess you like

Origin blog.csdn.net/qq_39208971/article/details/108286216