vue设置通用localStorage-工具方法

localStorage 用于长久保存整个网站的数据,保存的数据没有过期时间,直到手动去删除。

提示:

如果你只想将数据保存在当前会话中,可以使用 sessionStorage 属性, 该数据对象临时保存同一窗口(或标签页)的数据,在关闭窗口或标签页之后将会删除这些数据。

utils.js文件:

/**
 * 存储localStorage
 */
export const setStore = (name, content) => {
    if (!name) return;
    if (typeof content !== 'string') {
        content = JSON.stringify(content);
    }
    window.localStorage.setItem(name, content);
}

/**
 * 获取localStorage
 */
export const getStore = name => {
    if (!name) return;
    return window.localStorage.getItem(name);
}

/**
 * 删除localStorage
 */
export const removeStore = name => {
    if (!name) return;
    window.localStorage.removeItem(name);
}

用法:

/**导入localStorage*/
import{setStore,getStore} from @/config/utils
setStore('userName',xxxxx)/**存储用户名值为xxxx*/
getStore('userName')/**获取用户名称*/

猜你喜欢

转载自blog.csdn.net/pinhmin/article/details/129160854