vue项目笔记(22)-使用keep-alive优化网页代码

使用keep-alive优化网页代码

在运行项后时,打开控制台的Network-XHR,点击城市切换,而后点击返回到首页,我们发现index.json请求了两次,在产生路由切换的时候,ajax请求都会重新进行请求,严重影响网页性能。如果可以发起一次请求就好了。

解决方法:用<keep-alive></keep-alive>包裹<router-view />

// App.vue组件
<keep-alive>
        <router-view/>
</keep-alive>

此时,项目仍存在一些问题,当切换到某一指定的城市之后,home页面应该所切换到的城市的相关内容。所以,在进行ajax请求的时候,我们应该写到对应的参数(指定的城市),该参数是vuex中存储的当前所在的城市。因此,我们在Home组件中引入vuex,具体具体代码变动如下:

(1)引入vuex, import { mapState } from 'vuex'

(2)修改请求的url,/api/index.json?city='+ this.city

<script>
  import axios from "axios"
  import { mapState } from 'vuex'
  import HomeHeader from "./components/Header";
  import HomeSwiper from "./components/Swiper"
  import HomeIcons from "./components/Icons"
  import HomeRecommend from "./components/Recommend"
  import HomeWeekend from "./components/Weekend"
  export default {
    name: "Home",
    data() {
      return {
        iconList:[],
        recommendList:[],
        swiperList:[],
        weekendList:[]
      };
    },
    computed:{
      ...mapState(['city'])
    },
    components: {
      HomeHeader,
      HomeSwiper,
      HomeIcons,
      HomeRecommend,
      HomeWeekend
    },
    mounted(){
      this.getHomeInfo();
    },
    methods: {
      getHomeInfo(){
        // axios返回的结果是一个promise对象
        axios.get('/api/index.json?city='+ this.city).then(
          // 注意:这里绝对不可以写成this.getHomeInfoSucc(),否则请求的结果会是undefined
          this.getHomeInfoSucc
        )
      },
      getHomeInfoSucc(res){
        console.log(res);
        res = res.data;
        if (res.ret && res.data) {
          this.swiperList = res.data.swiperList;
          this.iconList = res.data.iconList;
          this.recommendList = res.data.recommendList;
          this.weekendList = res.data.weekendList;
        }
      }
    }
  };
</script>

此时,请求中应该是对应城市的请求信息了。

随后,我们清空控制台,重新选择城市,比如“三亚”,但是我们发现,因为keep-alive缓存的原因,并没有发起任何ajax请求。“三亚”对应的相关信息仍未展示。

所以,如果我们要显示“三亚”的相关信息,我们必须改变缓存中的数据。在使用keep-alive时,vue中会多出一个生命周期钩子activated。在首次进入home页面的时候,mounted,activated均会执行,但是当再次切换到home页面的时候(页面重新被显示的时候),只有activated会执行。

代码修改如下:

(1)data中定义lastCity,表示缓存中的城市

lastCity: '',

(2)钩子函数mounted中

this.lastCity = this.city;

(3)钩子函数mounted中,做出判断(如果再次进入的页面不是之前的页面,便发起ajax请求,并且修改缓存中的城市)

if (this.lastCity !== this.city) {
        this.lastCity = this.city;
        this.getHomeInfo();
}

猜你喜欢

转载自blog.csdn.net/qq_41115965/article/details/81736351
今日推荐