需求: h5表单页面,跳转到指定页面时,表单页面数据储存:
1.采用keepAlive坑太多,数据偶尔丢失;
2.可以使用vuex:将表单页面数据存入store,回来时再将所需数据取出。
表单页面:
// 路由离开的时候,判断跳转去的页面路由是否需要缓存
beforeRouteLeave(to, from, next) {
if(to.name === "vote-application.vote.avatarPage") {
let data = {
formData:this.formData,
tab:this.tab,
projectList:this.projectList,
joinList:this.joinList,
sendList:this.sendList
}
//commit与mutations搭配使用(同步)
//store.commit('commit方法名',数据参数)
store.commit('SAVE_LIST',data);
}
next()
},
store.js文件:
import Vue from 'vue';
import Vuex from 'vuex';
import config from '@/config.js';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
//初始化定义数据state
voteList:{}
},
//这里不需要异步,就用mutations即可
actions: {},
mutations: {
/**
* 储存表单页面数据
* @param state
* @param data
*/
SAVE_LIST(state, data) {
//将获取到的data数据赋值给state中的voteList值存起来,方便到时侯在store的state中去取值
state.voteList = data || {}
},
},
modules: {},
});
表单页面:
<script>
//1.引入
import {mapState} from 'vuex'
//2.在computed中取出
computed:{
...mapState({
voteArr:state => state.voteList
})
},
//3.然后就可以在需要的地方使用
created() {
// 把存在vuex里面的值拿出来
this.tab = this.voteArr.tab
this.formData = this.voteArr.formData
this.projectList = this.voteArr.projectList
}
</script>