vue——頁面刷新數據丟失問題

參考: https://blog.csdn.net/aliven1/article/details/80743470
          https://blog.csdn.net/liang377122210/article/details/78880438
          https://blog.csdn.net/goodaxuan/article/details/82113123vue

 

個人需求: 進入商城後調接口獲取用戶id,並把id存入session中。以後跳轉頁面或刷新頁面時,直接從session中取出id,無需再調接口。ios

 

main.js文件中:vuex

import Vue from 'vue'; import App from './App'; import router from './router'; import Vuex from 'vuex'; ··· import store from './store'; //vuex部分
 Vue.prototype.$http = axios; axios.defaults.baseURL = '***'; axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; Vue.prototype.userInfo = function(succallback, failcallback) { var _this = this; if (_this.userId) { succallback && succallback(_this.userInfo); return; } if (sessionStorage.getItem("userMsg")) { let t = sessionStorage.getItem("userMsg"), obj = JSON.parse(t), userMsg = obj.userMsg; _this.uMID = userMsg.uMID;
    _this.userInfo = { 'uMID': userMsg.uMID
 }; succallback && succallback(_this.userInfo); } else { _this.$http.get('***').then(function(res) { if (res.status === 200 && res.data.result === "0") { var data = res.data.message;
          _this.userInfo = { 'uMID': data.uMID
 }; _this.uMid = data.uMID;
          _this.$store.commit('set_userMsg', data); sessionStorage.setItem("userMsg", JSON.stringify(_this.$store.state)); //在頁面加載時讀取sessionStorage裏的狀態信息
          if (sessionStorage.getItem("userMsg")) { _this.$store.replaceState(Object.assign({}, _this.$store.state, JSON.parse(sessionStorage.getItem( "userMsg")))); } //在頁面刷新時將vuex裏的信息保存到sessionStorage裏
          window.addEventListener("beforeunload", () => { sessionStorage.setItem("userMsg", JSON.stringify(_this.$store.state)) }) succallback && succallback(_this.userInfo); } }) .catch(function(error) { console.log(error); failcallback && failcallback(error); }); } }; new Vue({ el: '#app', router, store, data() { return { uMID: '' } }, components: { App }, template: '<App/>' })

 

store.js:axios

import Vue from "vue"; import Vuex from "vuex"; Vue.use(Vuex); export default new Vuex.Store({ state: { userMsg: '', userId: '' }, getters: { userId: state => state.userId }, mutations: { changeUserId(state, userId) { state.userId = userId; }, set_userMsg(state, data) { state.userMsg = data } }, actions: {}, modules: {} });

 

 

組件中:session

··· data() { return { uMID: '' } }, created() { let _this = this; _this.getUser(); }, methods: { getUser: function() { let _this = this; _this.userInfo(function(userId) { _this.uMID = userId.uMID; ··· //須要uMID的操做最好在這裏進行
 }); } }···
相關文章
相關標籤/搜索