vuex stateリフレッシュステータスが失われました

1034 ワード

1、storeのデータは実行メモリに保存されているため、ページがリフレッシュされるとvueインスタンスが再ロードされ、storeのデータが再割り当てされます.2、解決策
  • store.js
  • import Vue from 'vue'
    import Vuex from 'vuex'
    Vue.use(Vuex)
    
    //   
    const state = {
      name: localStorage.getItem("name"), //    --  
    }
    //   
    const mutations = {
      name(state, str) {//  
        localStorage.setItem("name", str);
        state.name = str;
      },
    }
    //         10
    const getters = {}
    //   
    const actions = {
      setName(context,str){
        context.commit("name", str);
      }
    }
    export default new Vuex.Store({
      state,
      mutations,
      actions
    })
    
  • コールstore
  • import store from '@store/index.js'
    export default {
      store,
      mounted(){
        this.$store.dispatch('setName','  ')
      }
    }
    
  • b.vue取得
  • import store from '@store/index.js'
    export default {
      store,
      mounted(){
        console.log(this.$store.state)
        console.log(this.$store.state.name)
      }
    }