頁面刷新後,vuex中數據丟失、清空的解決方案 vuex-persistedstate

場景之一

應用API進行用戶身份驗證,將登陸狀態保存爲Vuex狀態中的布爾值。

當用戶登陸時,設置了 登陸狀態 並相應地有條件地顯示 登陸/註銷 按鈕。

可是當刷新頁面時,vue應用程序的狀態將丟失並重置爲默認值。

這致使的問題就是:即便用戶登陸了,但刷新頁面時,登陸狀態 也會設置爲false, 這樣即便用戶保持登陸狀態,也會顯示登陸按鈕而不是註銷按鈕....

怎麼作才能防止這種行爲vue

解決方案

可使用 vuex-persistedstate 。這是一個用於 vuex 在頁面刷新之間處理和存儲狀態的插件。git

示例代碼:github

import createPersistedState from 'vuex-persistedstate'

const store = new Vuex.Store({
  // ...
  plugins: [
    createPersistedState()
  ]
})

以上是將狀態保存在 localStorage ,也可使用 js-cookie 將狀態保存在cookievuex

import { Store } from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import * as Cookies from 'js-cookie'
 
const store = new Store({
  // ...
  plugins: [
    createPersistedState({
      storage: {
        getItem: key => Cookies.get(key),
        // 參考 https://github.com/js-cookie/js-cookie#json
        setItem: (key, value) => Cookies.set(key, value, { expires: 3, secure: true }),
        removeItem: key => Cookies.remove(key)
      }
    })
  ]
})

總結:npm

  1. 須要安裝 js-cookie
  2. getItem 加載保存的狀態
  3. setItem 保存狀態
  4. removeItem 刪除保存的狀態

vuex-persistedstate 文檔和安裝說明:https//www.npmjs.com/package/vuex-persistedstatejson

相關文章
相關標籤/搜索