在vue中封裝localStorage

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裏面查看

在這裏插入圖片描述在這裏插入圖片描述
這裏就完成了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章