1.問題:在vue項目中,刷新頁面之后,我當前打開的所有菜單,都消失,我如何實現刷新之后頁面仍然是刷新之前的狀態
效果圖:
解決方法:
使用vuex作狀態管理: 將vuex里面的數據同步更新到localStorage里面,改變vuex里的數據,便觸發localStorage.setItem
方法,
實現代碼:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
function storeLocalStore (state) {
window.localStorage.setItem("userMsg",JSON.stringify(state));
}
const store = new Vuex.Store({
modules: {
tags:[],
curTagsIndex:"-1",
},
mutations: {
SET_CURTAGS: (state, index) => {
state.curTagsIndex = index
},
}
})
export default store
2在 App.vue
的 created
鈎子函數里寫下了如下代碼;
//在頁面加載時讀取localStorage里的狀態信息
localStorage.getItem("userMsg") && this.$store.replaceState(Object.assign(this.$store.state,JSON.parse(localStorage.getItem("userMsg"))));
//在頁面刷新時將vuex里的信息保存到localStorage里
window.addEventListener("beforeunload",()=>{
localStorage.setItem("userMsg",JSON.stringify(this.$store.state))
})
原文鏈接:https://blog.csdn.net/aliven1/article/details/80743470