首頁  >  問答  >  主體

在Vue中使用localStorage。在哪裡需要使用它?

<p>我想使用localStorage,這樣當頁面重新載入時,資料能夠保存下來。 <br /><br />我使用Vuex來追蹤一個人是否已註冊。並且希望當頁面加載時,這個人已經註冊。 <br /><br />我的Vuex程式碼如下:</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>我的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> 在重新載入頁面時,最好在哪裡使用localStorage來保存IS_REGISTERED? </p><p><br /></p>
P粉122932466P粉122932466442 天前483

全部回覆(1)我來回復

  • P粉680000555

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

    Translation: 我自己解決了這個問題,// npm-> npm install vuex-persistedstate // OR // yarn-> yarn add vuex-persistedstate

    在我的store中,需要像這樣添加:


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

    回覆
    0
  • 取消回覆