Vuex refreshes and saves data (vue, uniapp)

Table of contents

 

Window object implementation, only for browser projects

1. Browser local storage

2.uniapp uses vuex data persistence (plug-in)

uniapp app local storage


Window object implementation, only for browser projects

1. Browser local storage

Copy it to the script tag of app.vue directly

Temporary storage: sessionStoryage

Permanent storage: localStoryage

export default {
  name: "App",
  created() {
    //在页面加载时读取sessionStorage里的状态信息
    if (sessionStorage.getItem("store")) {
      this.$store.replaceState(
        Object.assign(
          {},
          this.$store.state,
          JSON.parse(sessionStorage.getItem("store"))
        )
      );
    }
    //在页面刷新时将vuex里的信息保存到sessionStorage里
    window.addEventListener("beforeunload", () => {
      sessionStorage.setItem("store", JSON.stringify(this.$store.state));
    });
  },
};

 

2.uniapp uses vuex data persistence (plug-in)

 download

npm install --save vuex-persistedstate

 Use in store/index.js

I used the modular one here, it doesn’t affect it, it’s all put at the end

import Vue from "vue"
import Vuex from 'vuex'
import login from "./login/index.js"
import createPersistedState from 'vuex-persistedstate'
Vue.use(Vuex)

const store = new Vuex.Store({
	modules: {
		login
	},
	plugins: [createPersistedState()] // 数据持久化
})

export default store

plugins: [createPersistedState()] // data persistence

uniapp app local storage

1. Get the local storage data directly on the state in vuex, use the initialized data

 2. Write the storage method and the acquisition method in the mutations (in fact, you don’t need to write the acquisition method, because the above is directly obtained)

The storage method is called in the life cycle when you modify the data or exit the application

        // 获取本地数据
        getvuex(state, val) {
			state = uni.getStorageSync("vuex")
			console.log(state);
		},
        // 存储到本地
		setvuex(state, val) {
			uni.setStorageSync("vuex", state)
			console.log(state);
		},

 

 Then it works!

Guess you like

Origin blog.csdn.net/weixin_70563937/article/details/127622636