localStorage
-
localStorage 和 sessionStorage 屬性允許在瀏覽器中存儲 key/value 對的數據。
-
localStorage 用於長久保存整個網站的數據,保存的數據沒有過期時間,直到手動去刪除。
-
localStorage 屬性是隻讀的。
-
提示: 如果你只想將數據保存在當前會話中,可以使用 sessionStorage
屬性,改數據對象臨時保存同一窗口(或標籤頁)的數據,在關閉窗口或標籤頁之後將會刪除這些數據。
1.首先在你的vue項目中創建一個storage.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)
}
這裏簡單說明一下:name指的是儲存的名字,content指的是你要儲存到裏面的值。
2.在main.js裏面全局註冊一下
import { setStore, getStore, removeStore } from '@/libs/storage'
Vue.prototype.setStore = setStore
Vue.prototype.getStore = getStore
Vue.prototype.removeStore = removeStore
3.這樣子就完成了,然後你就可以在你需要的地方引入了,例子如下:
mounted () {
this.setStore('aaa', '123')
}
然後我們可以在谷歌瀏覽器裏面的application裏面查看
這裏就完成了。