在编写项目的时候会遇到刷新页面时,vuex中的状态会被重置的原因
- 产生原因
- 解决方案
- 案例
产生原因:
由于store里的数据是保存在运行内存中的,当页面刷新时,页面会重新加载vue实例,store里面的数据就会被重新赋值
解决方案:
当用户修改了state状态刷新的时候vuex实现又被重新加载了, 那怎么办呢? 这时候我们可以利用BOM的sessionStorage来进行存储。
为什么选择sessionStorage的原因:
localStorage是永久存储在本地,除非你主动去删除;
sessionStorage是存储到当前页面关闭为止;
cookie则根据你设置的有效时间来存储,但缺点是不能储存大数据且不易读取。
案例:
export default new Vuex.Store({
state: {
name:'',
age:18,
weight:50
},
mutations: {
changeName(state,params){
state.name=params
},
changeAge(state,params){
state.age=params
}
},
actions: {
increment(context,prms){
context.commit('changeAge',prms)
}
},
modules: {
}
})
<template>
<div class="contain-wrap">
<input type="text" v-model="content">
<input type="button" @click="btnClick()" value="使用sessionStorage来解决刷新数据重置问题">
</div>
</template>
<script>
export default {
name: "index",
data() {
return {
content:''
};
},
methods:{
btnClick(){
this.$store.commit('changeName',this.content);
// this.$store.commit('changeAge',this.content);
// this.$store.dispatch('increment',this.content);
this.$router.push('/material');
}
},
created() {},
};
</script>
在app.vue的created生命周期函数中加入下列代码:
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<script>
export default {
created(){
//在页面加载时读取sessionStorage里的状态信息
if (sessionStorage.getItem("store") ) {
//this.$store.replaceState是vue官方提供的一个api表示替换 store 的根状态
//里面的Object.assign()表示将store中的状态和sessionStorage中的状态进行合并
this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(sessionStorage.getItem("store"))))
}
//在页面刷新时将vuex里的信息保存到sessionStorage里
//beforeunload表示当浏览器窗口关闭或者刷新时,会触发beforeunload事件
window.addEventListener("beforeunload",()=>{
sessionStorage.setItem("store",JSON.stringify(this.$store.state))
})
}
}
</script>
结果:
效果:
总结:因此不管怎么刷新state状态都不会被重置了