每个页面通过computed和watch监测vuex参数,在参数变化时请求ajax更新数据。
在公共组件改变参数时,所有页面都会去重新请求数据,当前页面根据数据重新渲染,但切换回其他页面时,由于keep-alive,页面没有变化。
//vuex store.js
const state = {
classes: "",
day: "",
}
const mutations = {
updateClasses(state,payload) {
state.classes=payload
},
updateDay(state,payload) {
state.day=payload
},
}
//vue computed
classes() {
return this.$store.state.classes
},
day() {
return this.$store.state.day
},
//vue watch
classes(val) {
this.updateClassChange()//ajax请求
},
day(val) {
this.updateDayChange()//ajax请求
}
//公共组件
this.$store.commit('updateClasses', {this.classs})
this.$store.commit('updateDay', {this.day})
第一步:判断此时路由是否是当前页面,避免多余的数据请求,只有当前页面重新请求数据
watch: {
classes(val) {
if(this.$route.name=="index") {
this.updateClassChange()
}
},
day(val) {
if(this.$route.name=="index") {
this.updateDayChange()
}
}
},
第二部:是用钩子函数activated,每切换路由时重新加载,避免参数变化时页面没有变化
activated() {
if(this.$route.name=="index"){
this.init()
}
},
该方案问题:参数不变时,虽然不重新渲染,但每次切换路由也会重新请求
在vue为每一个页面存储一个公共组件参数,使个页面参数相互不干扰,keep-alive也不混乱
//vuex store.js
const state = {
classesObj:{
index:"",
addict:"",
consume:"",
mental:""
},
dayObj:{
index:"",
addict:"",
consume:"",
mental:""
},
}
const mutations = {
setClassesObj(state,payload){
if(payload.index){
state.classesObj.index=payload.index
}
if(payload.addict){
state.classesObj.addict=payload.addict
}
if(payload.consume){
state.classesObj.consume=payload.consume
}
if(payload.mental){
state.classesObj.mental=payload.mental
}
},
setDayObj(state,payload){
if(payload.index){
state.dayObj.index=payload.index
}
if(payload.addict){
state.dayObj.addict=payload.addict
}
if(payload.consume){
state.dayObj.consume=payload.consume
}
if(payload.mental){
state.dayObj.mental=payload.mental
}
},
}
//vue computed
classes() {
return this.$store.state.classesObj[this.$route.name]
},
day() {
return this.$store.state.dayObj[this.$route.name]
},
//vue watch
classes(val) {
this.updateClassChange()//ajax请求
},
day(val) {
this.updateDayChange()//ajax请求
}
//公共组件
this.$store.commit('setClassesObj', {[this.$route.name]:this.classs})
this.$store.commit('setDayObj', {[this.$route.name]:this.day})