数据本地存储方法封装(笔记)localStorage、sessionStorage

数据本地存储方法封装(笔记)localStorage、sessionStorage

方法:

import storage from 'good-storage'

const SELLER_KEY = '__seller__'

export function saveToLocal(id, key, val) {
  const seller = storage.get(SELLER_KEY, {})
  if (!seller[id]) {
    seller[id] = {}
  }
  seller[id][key] = val
  storage.set(SELLER_KEY, seller)
}

export function loadFromLocal(id, key, def) {
  const seller = storage.get(SELLER_KEY, {})
  if (!seller[id]) {
    return def
  }
  return seller[id][key] || def
}

使用:

import { saveToLocal, loadFromLocal } from 'common/js/storage'

// 存值
this.favorite = loadFromLocal(this.seller.id, 'favorite', false)

// 取值
saveToLocal(this.seller.id, 'favorite', this.favorite)

 备注:存储api

 import storage from 'good-storage'
 
 // localStorage
 storage.set(key,val) 
 
 storage.get(key, def)
 
 // sessionStorage
 storage.session.set(key, val)
 
 storage.session.get(key, val)

感谢黄轶老师。

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(vue)