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

Logo

前往低代码交流专区

更多推荐