目录
window对象实现,只能用于浏览器项目使用
1.浏览器本地存储
复制到app.vue的script标签直接就可以了
临时存储:sessionStoryage
永久存储: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使用vuex数据持久化(插件)
下载
npm install --save vuex-persistedstate
在store/index.js里面使用
我这里使用了模块化的,不影响,都是放最后面
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()] // 数据持久化
uniapp app本地存储
1.在vuex里面的state上面直接获取本地存储数据 没有就用初始化的数据
2.在mutations里面写存储方法和获取方法(其实不需要写获取方法,因为上面就直接获取了)
存储方法在你修改了数据或者退出应用的生命周期里面调用
// 获取本地数据
getvuex(state, val) {
state = uni.getStorageSync("vuex")
console.log(state);
},
// 存储到本地
setvuex(state, val) {
uni.setStorageSync("vuex", state)
console.log(state);
},
然后就可以了!