如上图所示,当我们在使用路由在首页和城市列表页之间进行切换时,它会反复访问 index.json(首页数据) 和 city.json(城市列表页数据),而大多数时候,这里的数据都是一样的,不需要反复请求。
使用<keep-alive>将请求的数据缓存到内存中,当再次访问时,直接从内存中取数据即可!案例如下:
<template> <div id="app"> <keep-alive> <router-view/> </keep-alive> </div> </template>如上例所示,当主界面随着我们在城市列表界面的选择而改变时,这个时候,使用 <keep-alive> 缓存的数据就无效了,这种情况如何应对?
备注: 1.mounted ():当配合 <keep-alive> 使用时,mounted ()只在页面挂载时调用(只调用一次);普通情况下,每次组件出现时,都会被调用。 2.activated ():当配合 <keep-alive> 使用时,activated ()生命周期方法才会出现activated ()在页面由隐藏到出现时调用(每次都调用) 1.请求路径上加上城市参数,如下:
getHomeInfo () { Axios.get('/api/index.json?city=' + this.city) .then(this.getHomeInfoSucc) },2.在 mounted () 中记录本次访问的城市
mounted () { this.lastCity = this.city this.getHomeInfo() },3.在 activated () 中比较上衣访问的城市和本次访问的城市,若不一致,则重新访问
activated () { //当上一次访问的城市和本次访问的城市不同时,重新请求数据 if(this.lastCity != this.city) { this.lastCity = this.city this.getHomeInfo() } }