描述:
文章列表:
点击title跳转详情:
如果刷新网页,数据清空,如何解决?
使用vuex-along插件。
- 创建article作为vuex的一个新的module
const article={
state:{
myArticle:{
id:'',
title:'',
content:'',
authorId:1,
type:2,
bgmImg:''
}
},
mutations:{
SET_ARTICLE:(state,article)=>{
state.myArticle.id = article.id;
state.myArticle.title = article.title;
state.myArticle.content = article.content;
state.myArticle.authorId = article.authorId;
state.myArticle.type = article.type;
state.myArticle.bgmImg = article.bgmImg;
},
RESET_ARTICLE:(state)=>{
state.myArticle.id = '';
state.myArticle.title = '';
state.myArticle.content = '';
state.myArticle.authorId = '';
state.myArticle.type = '';
state.myArticle.bgmImg = '';
}
},
actions:{
setArticle({commit},row){
commit('SET_ARTICLE',row);
},
resetArticle({commit}){
commit('RESET_ARTICLE');
}
}
}
export default article
- 在index.js中使用vuex-along
先下载
npm install vuex-along --save
再引用
import createVuexAlong from 'vuex-along'
最终的index.js
重点:
- 在newArticle.vue里
created(){
if(this.$route.params.row){
this.$store.dispatch('setArticle',this.$route.params.row);
let row =this.$route.params.row;
this.myArticle.id = row.id;
this.myArticle.title = row.title;
this.myArticle.content = row.content;
this.myArticle.bgmImg = row.bgmImg;
this.buttonStatus = 'update';
}else if(JSON.parse(sessionStorage.getItem("article-vuex-along")).root.myArticle.myArticle) {
let obj = JSON.parse(sessionStorage.getItem("article-vuex-along"));
let row = obj.root.myArticle.myArticle;
this.myArticle.id = row.id;
this.myArticle.title = row.title;
this.myArticle.content = row.content;
this.myArticle.bgmImg = row.bgmImg;
this.buttonStatus = 'update';
}
},
- 以上操作可以实现跳转到详情页再刷新浏览器保证数据不清空,但是如果我不从文章列表页跳转直接点击新建文章数据仍然在,所以要在vue的destroyed函数里给缓存中的数据初始化为空。
destroyed(){
this.$store.dispatch('resetArticle');
}
article.js中
resetArticle({commit}){
commit('RESET_ARTICLE');
}
RESET_ARTICLE:(state)=>{
state.myArticle.id = '';
state.myArticle.title = '';
state.myArticle.content = '';
state.myArticle.authorId = '';
state.myArticle.type = '';
state.myArticle.bgmImg = '';
}