赞
踩
storage会根据传入的参数类型自动进行json转换,不用再自己手动写JSON.stringify()和JSON.parse(),需要的小伙伴直接复制到项目中就能使用
- class Storage {
- constructor() {}
-
- /**
- * 获取
- * @param {String} key
- * @returns
- */
- getStorage(key) {
- if(!key) {
- console.error(new Error('function getStorage params is undefined'))
- return
- }
-
- const value = window.localStorage.getItem(key)
- try {
- const object = JSON.parse(value)
- return object
- }
- catch (error) {
- return value
- }
- }
-
- /**
- * 设置
- * @param {String} key
- * @param {any} value
- * @returns {any}
- */
- setStorage(key, value) {
- if(!key && !value) {
- console.error(new Error('function setStorage params is undefined'))
- return
- }
-
- if(typeof value === 'object') {
- const jsonString = JSON.stringify(value)
- window.localStorage.setItem(key, jsonString)
- }
- else {
- window.localStorage.setItem(key, value)
- }
- }
-
- /**
- * 移除
- * @param {String} key
- * @returns
- */
- removeStorage(key) {
- if(!key) {
- console.error(new Error('function removeStorage params is undefined'))
- return
- }
- window.localStorage.removeItem(key)
- }
-
- /**
- * 清除
- */
- clearStorage() {
- window.localStorage.clear()
- }
- }
-
- const storage = new Storage()
-
- export default storage
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。