1. vuex
persistPlugin.js 文件
javascript
const routerKey = "ROUTER_KEY";
export default (store) => {
// 刷新页面时,存储改变的数据
window.addEventListener("beforeunload", () => {
localStorage.setItem(routerKey, JSON.stringify(store.state.router.routers));
});
// 将存储的数据取出,存到全局的状态管理里面
try {
const localState = localStorage.getItem(routerKey);
if (localState) {
store.dispatch("router/setRouters", JSON.parse(localState));
store.state.router;
}
} catch (error) {
console.log("本地存储数据异常");
}
};
modules/router.js文件
javascript
const state = {
routers: [],
}
const mutations = {
SET_ROUTERS(state, menuData) {
state.routers = menuData
},
}
const actions = {
setRouters({ commit }, menuData) {
commit('SET_ROUTERS', menuData)
},
}
export default {
namespaced: true,
state,
mutations,
actions
}
store/index.js
javascript
import Vue from "vue";
import Vuex from "vuex";
import router from "./modules/router";
import getters from "./getters";
//数据持久化
import persistPlugin from "./persistPlugin.js";
Vue.use(Vuex);
const store = new Vuex.Store({
modules: {
router,
},
getters,
state: {},
mutations: {},
actions: {},
plugins: [persistPlugin],
});
export default store;
** 2. pinia **
persistPlugin.js 文件
javascript
import { useRouterStore} from '@/stores/routerStoreControl';
import { storeToRefs } from 'pinia';
const routerStore = useRouterStore();
const { routers } = storeToRefs(routerStore);
const routerKey= "ROUTER_KEY";
export default (context) => {
const { store } = context;
const key = store.$id;
// 判断存储的数据是否为路由
if(key == 'router'){
// 刷新页面时,存储改变的数据
window.addEventListener("beforeunload", () => {
localStorage.setItem(routerKey, JSON.stringify(store.$state.routers));
});
// 将存储的数据取出,存到全局的状态管理里面
try {
const localState = localStorage.getItem(routerKey);
if (localState) {
routers.value = JSON.parse(localState);
}
} catch (error) {
console.log("本地存储数据异常");
}
}
};
routerStoreControl.js
javascript
import { defineStore } from 'pinia';
import { ref } from 'vue';
export const useRouterStore = defineStore('router', () => {
const routers = ref([]);
return { routers };
});
main.js
javascript
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia';
//数据持久化
import persistPlugin from "./persistPlugin.js";
const pinia = createPinia();
pinia.use(persistPlugin);
const app = createApp(App);
app.use(pinia);
app.mount('#app');