localStorage工具类
localStorageUtil.js
js
export default class LocalStorageUtil {
// 设置存储项
static setItem(key, value) {
if (typeof value === 'object') {
value = JSON.stringify(value);
}
window.localStorage.setItem(key, value);
}
// 获取存储项
static getItem(key) {
let value = window.localStorage.getItem(key);
if (value && (value.startsWith('{') || value.startsWith('['))) {
value = JSON.parse(value);
}
return value;
}
// 删除存储项
static removeItem(key) {
window.localStorage.removeItem(key);
}
// 清除所有存储
static clear() {
window.localStorage.clear();
}
}
使用
js
import LocalStorageUtil from './utils/localStorageUtil'
// 存储一个对象
LocalStorageUtil.setItem('user', { name: 'John', age: 30 });
// 获取这个对象
let user = LocalStorageUtil.getItem('user');
console.log(user.name); // 输出 "John"
// 删除这个对象
LocalStorageUtil.removeItem('user');
// 清除所有存储
LocalStorageUtil.clear();