"vuex-persistedstate to switch between sessionStorage and localStorage"
P粉295728625
P粉295728625 2023-08-25 23:06:52
0
1
517
<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粉295728625
P粉295728625

reply all(1)
P粉658954914

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!