美文网首页
在vue中封装localStorage

在vue中封装localStorage

作者: Nkero | 来源:发表于2020-08-26 16:05 被阅读0次

1.首先在vue项目中创建一个storage.js文件,代码如下:

/**
 * @param {String} name [储存的名字]
 * @param {String} content [储存的值]
 */
/**
 * 存储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)
}

2.在main.js里面全局注册

import { setStore, getStore, removeStore } from '存放storage.js的路径'
Vue.prototype.setStore = setStore
Vue.prototype.getStore = getStore
Vue.prototype.removeStore = removeStore

3.这样子就完成了,然后你就可以在你需要的地方引入了,例子如下:

 this.setStore('name', 'nameVal')

相关文章

网友评论

      本文标题:在vue中封装localStorage

      本文链接:https://www.haomeiwen.com/subject/lrqfsktx.html