search

Home  >  Q&A  >  body text

Using localStorage in Vue. Where do I need to use it?

<p>I want to use localStorage so that the data is saved when the page reloads. <br /><br />I use Vuex to track whether a person is registered. And hopefully when the page loads, the person is already registered. <br /><br />My Vuex code is as follows:</p><p><br /></p> <pre class="brush:php;toolbar:false;">export default { state:{ isRegistered:false }, actions:{ registrate({commit}) { commit("login") }, exit({commit}) { commit("logout") } }, mutations:{ login(state) { state.isRegistered=true; }, logout(state) { state.isRegistered=false } }, getters:{ IS_REGISTERED(state){ return state.isRegistered } } }</pre> <p>Links in my Vue.js</p> <pre class="brush:php;toolbar:false;"><template> <header class="hat"> <div class="header__buttons"> <div v-if="IS_REGISTERED" id="exit--tittle"> <button @click="exitFromSystem">Exit from system</button> </div> <router-link :to="{name:'registration'}"> <button id="registration" v-if="!IS_REGISTERED">Registration</button> </router-link> </div> </header> </template> <script> methods: { ...mapActions(["exit"]), exitFromSystem() { this.exit() // Look in Vuex }, }, </script></pre> <p> Where is the best place to use localStorage to save IS_REGISTERED when reloading the page? </p><p><br /></p>
P粉122932466P粉122932466485 days ago521

reply all(1)I'll reply

  • P粉680000555

    P粉6800005552023-08-04 16:48:47

    Translation: I solved this problem myself, // npm-> npm install vuex-persistedstate // OR // yarn-> yarn add vuex-persistedstate

    In my store, required Add it like this:


    import Vue from "vue"
    import Vuex from "vuex"
    import createPersistedState from "vuex-persistedstate";
    
    export default new Vuex.Store({
       modules:{
           // 
       },
       plugins:[createPersistedState()]
    }

    reply
    0
  • Cancelreply