search

Home  >  Q&A  >  body text

"vuex-persistedstate to switch between sessionStorage and localStorage"

<p>If the user selects the "Remember me" checkbox, I want to switch from sessionStorage to localStorage, while I use vuex-persistedstate</p> <pre class="brush:php;toolbar:false;">export default store(function (/* { ssrContext } */) { const Store = createStore({ state: { }, actions: { setLodingMode({ commit }, newMode) { commit("SET_LOADING_MODE", newMode); }, resetStates({ commit }) { commit("AUTHENTICATION_RESET_STATE"); commit("login/RESET_STATE"); }, }, modules: { login, authentication }, plugins: [createPersistedState()], }); return Store; });</pre> <p>The point is I want to make changes like this</p> <pre class="brush:php;toolbar:false;">state: { flag: false }, plugins: [ createPersistedState({ storage: flag ? window.localStorage : window.sessionStorage, }), ],</pre> <p>I want the flag to change based on the "Remember Me" checkbox the user selects when logging in, so when the user selects the checkbox, the flag becomes true and all the data is saved in localStorage</p> ;
P粉295728625P粉295728625451 days ago529

reply all(1)I'll reply

  • P粉658954914

    P粉6589549142023-08-26 11:07:29

    Per @Estus Flask's comment, I used a custom storage and managed the "remember me" option by calling localStorage directly and setting a flag in localStorage.

    plugins: [
          createPersistedState({
            paths: ["authentication.userAuthenticationInfo"],
            storage: {
              getItem(key) {
                if (localStorage.getItem("rememberMe") == 1) {
                  return localStorage.getItem(key);
                } else {
                  return Cookies.get(key);
                  //return sessionStorage.getItem(key);
                }
              },
              setItem(key, value) {
                if (localStorage.getItem("rememberMe") == 1) {
                  localStorage.setItem(key, value);
                } else {
                  Cookies.set(key, value);
                  //sessionStorage.setItem(key, value);
                }
              },
              removeItem(key) {
                if (localStorage.getItem("rememberMe") == 1) {
                  localStorage.removeItem(key);
                } else {
                  Cookies.remove(key);
                  //sessionStorage.removeItem(key);
                }
              },
            },
          }),
        ],

    And I clear localStorage on every logout or 401 response.

    reply
    0
  • Cancelreply