1.首先在vue項目中創(chuàng)建一個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')