手动写一个vuex的可持续化插件
手动写一个vuex的可持续化插件
建一个js
const KEY = "VUEX:STATE";export default (store) => {// 存window.addEventListener("beforeunload", () => {localStorage.setItem(KEY, JSON.stringify(store.state));});// 取const item = localStorage.getItem(KEY);if (!item) {return;}try {const originState = JSON.parse(item);store.replaceState(originState);} catch (e) {console.log("存储格式无效");}
};
使用
import { createStore } from "vuex";
import user from "./modules/user";
import persistPlugin from "./persistPlugin";export default createStore({plugins: [persistPlugin],state() {return {// 状态数据定义...aaa: 1111,};},mutations: {// 状态更改方法定义...},actions: {// 异步操作定义...},modules: {// 模块化状态管理...user,},
});