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')