Page refresh of data stored in vuex is not cached

html login.vue this is what the login needs to store

	this.$httpPostService('/member/user/doLogin',{username:that.userName, password:that.userPassword, code:that.verCode}).then(res => {
          console.log(res);
		  //JSON.stringify is to convert json objects into strings
          localStorage.setItem("userInfo", JSON.stringify(res)) //Only when the local storage page is refreshed, it will not be cleared
          this.$store.commit("setPrint",{ // This is a call to a method in musitations
            userInfo: res
          })

          this.$router.push("index");
        }).catch(err => {
          console.log(err)
        })

store.js create a store folder, put JS in main.js, import and register globally

main.js

		import Vue from 'vue'
		import App from './App'
		import router from './router'


		import {httpPostService,httpGetService} from "./network/axios";
		Vue.prototype.$httpPostService = httpPostService;
		Vue.prototype.$httpGetService = httpGetService;
		import store from './store/store' //This was introduced

		import vueTitle from 'vue-wechat-title' // Set title
		Vue.use(vueTitle)

		import Mint from 'mint-ui';
		Vue.use(Mint);
		import 'mint-ui/lib/style.css';
		import './assets/less/common.less'
		Vue.config.productionTip = false;

		/* eslint-disable no-new */
	new Vue({
		el: '#app',
		router,
		store,
		components: { App },
		template: '<App/>'
	})

store.js

	import Vue from 'vue';
	import Vuex from 'vuex';
	Vue.use(Vuex);

	const state = {
		userInfo: localStorage.getItem('userInfo') || {} //Data from cache
	};
	const getters = {};

	const actions = {};

	const mutations = {
		setPrint(state,userInfo){
		state.userInfo = userInfo;
	}

};

export default new Vuex.Store({
	state,
	getters,
	actions,
	mutations
})

Global registration needs to be in app.vue

	<template>
		<div id="app">
			<router-view/>
		</div>
	</template>

<script>
	export default {
	name: 'App',
	data(){
		return{

	}
},
mounted(){
//Read the status information in localStorage when the page is loaded
localStorage.getItem("userInfo") && 			this.$store.replaceState(Object.assign(this.$store.state,JSON.parse(localStorage.getItem("userInfo"))));

	//Save the information in vuex to localStorage when refreshing the page
	window.addEventListener("beforeunload",()=>{
 	 localStorage.setItem("userInfo",JSON.stringify(this.$store.state))
 	})
	}
}
</script>

epilogue

What vuex stores is memory, localStorage is the interface provided by the browser, and what lets you store is the interface, which is stored locally in the form of a file, which is the essential difference between them
 When localStorage saves an object, it needs to first convert the object to a json string, and then convert it to object form when getting it

Tags: Front-end Vue JSON less network

Posted on Fri, 08 Nov 2019 08:00:25 -0800 by HokieTracks