数据监听+本地存储
情景一:普通vue-cli3项目
在App.vue中,created生命周期写我们的监听方法
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))
})
},
并且在变动vuex数据的时候,一定要记得同时更改sessionStorage数据
/store/moudles/user.js
import store from '../index'
...
const mutations = {
SET_USER: (state, user) => {
state.user = user
sessionStorage.setItem('store', JSON.stringify(store.state))
}
}
...
情景二:uni-app项目
在App.vue中,created、onLaunch生命周期写我们的监听方法
export default {
created() {
// 页面加载时,读取sessionStorage中的状态信息
if (uni.getStorageSync('store')) {
//用本地数据替换vuex数据
this.$store.replaceState(Object.assign({}, this.$store.state, uni.getStorageSync('store')))
}
},
onLaunch: function() {
uni.setStorageSync('store', this.$store.state)
}
}
并且在变动vuex数据的时候,一定要记得同时更改Storage数据
/store/moudles/cart.js
import store from '../index'
const mutations = {
SET_CART: (state, cart) => {
state.cart = cart
uni.setStorageSync('store', store.state)
}
}