vuex state刷新狀態丟失

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)
  }
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Swift1> Swift和OC的區別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴謹 對...
    cosWriter閱讀 11,145評論 1 32
  • 1.ios高性能編程 (1).內層 最小的內層平均值和峰值(2).耗電量 高效的算法和數據結構(3).初始化時...
    歐辰_OSR閱讀 29,645評論 8 265
  • 1、通過CocoaPods安裝項目名稱項目信息 AFNetworking網絡請求組件 FMDB本地數據庫組件 SD...
    陽明AGI閱讀 16,018評論 3 119
  • 學校每周都會安排一節示范課。昨天,聽了六年級的《把掌聲分給她一半》。 張老師講述了2016里約奧運會中國女排奪冠的...
    涼月西風閱讀 263評論 0 2
  • 書在很多人眼中是知識的象征,那么書店便可以說是知識的集散地了。記得兒時買書時,見書如見嗜物,硬擠推搡入內,在書堆內...
    B612上的小橙子閱讀 182評論 1 1