因为 Vuex 是状态保存,所以页面刷新,数据会丢失,这个时候需要保存数据到本地
页面刷新时 > state
保存到 localStorage
页面进入时 > 获取 localStorage
合并到 state
App.vue
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<script>
export default {
name: "App",
components: {
},
beforeCreate() {
const Store = JSON.parse(localStorage.getItem('Store'))
this.$store.replaceState(Object.assign(this.$store.state,Store))
},
mounted() {
window.addEventListener('beforeunload',()=>{
localStorage.setItem('Store',JSON.stringify(this.$store.state))
})
}
};
</script>