@H_502_0@在Vue单页应用中,如果在某一个具体路由的具体页面下点击刷新,那么刷新后,页面的状态信息可能就会丢失掉。这时候应该怎么处理呢?如果你也有这个疑惑,这篇文章或许能够帮助到你
@H_5020@
一、问题
@H502_0@现在产品上有个需求:单页应用走到某个具体的页面,然后点击刷新后,刷新的页面要与刷新前的页面要保持一致。
@H_502_0@这时候就需要我们保存刷新之前页面的状态。
@H_502_0@
二、一种解决方案
@H_5020@在这个Vue单页应用中,王二是用Vuex作为状态管理的,一开始王二的思路是将Vuex里的数据同步更新到localStorage里。
@H502_0@即:一改变vuex里的数据,便触发localStorage.setItem 方法,参考如下代码:
<div class="jb51code">
<pre class="brush:js;">
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)
function storeLocalStore (state) {
window.localStorage.setItem("userMsg",JSON.stringify(state));
}
export default new Vuex.Store({
state: {
username: "王二",schedulename: "标题",scheduleid: 0,},mutations: {
storeUsername (state,name) {
state.username = name
storeLocalStore (state)
},storeSchedulename (state,name) {
state.schedulename = name
storeLocalStore (state)
},storeScheduleid (state,id) {
state.scheduleid = Number(id)
storeLocalStore (state)
},}
})