vuex data persistence solution

1. Why does vuex data need to be persisted?

 因为vuex是基于内存,存在内存中的,当网页刷新之后就没有了,不会持久化储存

2. vuex persistence implementation plan

1. Use vuex-persistedstate

<1> Install a vuex plug-in vuex-persistedstate to support vuex state persistence

npm i vuex-persistedstate -S

Note: This plug-in should be a production dependency package, so you need -S
in package.json

Insert image description here

<2> Configure the store
to create a new index.js file in the src/store folder

import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate'
Vue.use(Vuex);
const config = {
    
    
    state: {
    
    
        isLogin: false,
    },
    getters: {
    
    
        
    },
    mutations: {
    
    
    
    },
    actions: {
    
    
	},
	modules: {
    
    
	    dict
	},
	plugins: [
	   createPersistedstate()
	],
}

const store = new Vuex.Store(config);
export default store;

<3> Introduced in main.js

import Vue from "vue";
import App from "./App.vue";
import router from "./router/index";
import store from "./store/index";
Vue.config.productionTip = false;
new Vue({
    
    
  store,
  router,
  render: h => h(App)
}).$mount("#app");

2. Use localStorage or sessionStorage

<1>Create a new vuexPersist.js file (actually the encapsulation of the plug-in for solution one)

// 从本地存储中获取数据
function getState(key) {
    
    
  try {
    
    
    const serializedState = localStorage.getItem(key);
    if (serializedState === null) {
    
    
      return undefined;
    }
    return JSON.parse(serializedState);
  } catch (err) {
    
    
    console.error('Error loading state from localStorage:', err);
    return undefined;
  }
}

// 将数据保存到本地存储中
function saveState(key, state) {
    
    
  try {
    
    
    const serializedState = JSON.stringify(state);
    localStorage.setItem(key, serializedState);
  } catch (err) {
    
    
    console.error('Error geting state to localStorage:', err);
  }
}

// Vuex 数据持久化插件
export function createPersistedState(key) {
    
    
  return (store) => {
    
    
    // 初始化时从本地存储中加载状态
    const savedState = getState(key);
    if (savedState) {
    
    
      store.replaceState(savedState);
    }

    // 监听 Vuex state 的变化并保存到本地存储中
    store.subscribe((mutation, state) => {
    
    
      saveState(key, state);
    });
  };
}

<2>Introduced in the store/index.js file

import Vue from "vue";
import Vuex from "vuex";
import {
    
     createPersistedState } from './vuexPersist'; 
Vue.use(Vuex);

export default new Vuex.Store({
    
    
  state: {
    
    
	 name: '张三' 
  },
  getters: {
    
    },
  mutations: {
    
    
	  updateName (state, payload) {
    
    
	    state.name = payload;
	  },
  },
  actions: {
    
    },
  modules: {
    
    },
  plugins: [
      createPersistedState('storageData')   
  ]
});

<3>Test effect

<template>
  <div class="about">
    <h1>{
    
    {
    
     name }}</h1>
	
	<span @click="changeName">change</span>
  </div>
</template>


<script>
import {
    
     mapState } from "vuex"

export default{
    
    
	data(){
    
    
		return{
    
    
			
		}
	},
	computed:{
    
    
		...mapState(['name'])
	},
	methods:{
    
    
		
		changeName(){
    
    
		   this.$store.commit('updateName', {
    
     name: '李四', age: 24, sex:'男'})	
		}
	}
}	
</script>

Other options
: Use the backend API: If your application needs persistent data to interact with the backend server, you can add asynchronous operations in the Vuex store to send the data to the backend API for storage. When the application initializes, you can get data from the backend API and update Vuex's state.

Using IndexedDB: IndexedDB is an advanced native database solution provided by the browser. You can use IndexedDB to store and retrieve Vuex data. You can write logic for IndexedDB in the Vuex store and load data from IndexedDB when the application is initialized.

Guess you like

Origin blog.csdn.net/to_prototy/article/details/132198599