城市选择页面的请求只发送一次,选择的城市与上次缓存的不同时才再次发送首页的请求
1.App组件中
使用keep-alive
将路由包裹进行缓存,首页的请求和城市选择页面的请求都只发送一次
<template>
<div id="app">
<!-- 显示当前路由地址所对应的内容 -->
<keep-alive>
<router-view/>
</keep-alive>
</div>
</template>
2.Home组件中
根据当前选择的城市与上次缓存的城市判断是否需要再次请求首页的数据
使用keep-alive
后,组件多了一个生命周期钩子函数activited
,每次从城市选择页面跳回首页时都会执行这个钩子函数;而mounted
钩子函数只在首次加载页面时执行。
data () {
return {
lastCity: '',//保存上一次缓存的城市
swiperList: [],
iconList: [],
recommendList: [],
weekendList: []
}
},
methods: {
getHomeInfo () {
axios.get('/api/index.json?city=' + this.$store.state.city)//发送请求时将请求的城市带上
.then(this.getHomeInfoSucc)
},
},
mounted () { //只首次加载页面时执行
this.lastCity = this.$store.state.city//选择完城市后,store中的数据更新,并将最新的城市数据作为上一次城市的数据存储下来
this.getHomeInfo()
},
activated () {
if (this.lastCity !== this.$store.state.city) { //如果选择的城市跟上一次不同,store中的数据会变化
this.getHomeInfo()
this.lastCity = this.$store.state.city
}
}