Vue学习笔记-项目开发3.12使用keep-alive和activated优化网页功能

怎甘沉沦 提交于 2020-03-12 11:32:39

一、原因分析

       1、每一次页面的跳转都会发送一次请求,获取一次数据,这样在页面没有改动的情况下极大的耗费了资源,所以需要优化
在这里插入图片描述
       是由于在入口文件中有mounted函数,每次都会加载,导致每次页面切换都会重新加载数据
在这里插入图片描述
       2、通过增加keep-alive进行优化,在数据加载过一次之后,会保存起来,下次直接在缓存中获取,减少请求次数。在根节点上增加
在这里插入图片描述
二、activated 优化
       每次页面切换,如果没有数据的变化可以直接使用缓存中的数据,但是如果数据变化的话,那么缓存中的数据也要随之变化,此时keep-alive就不能满足要求,需要引入activated ,keep-alive的加入使得每次页面切换的时候mounted只记载一次,但是activated则每次页面变化都会加载,所以可以通过activated来实现我们在数据变化后的动作

<template>
  <div>
    <home-header></home-header>
    <home-swiper :list="swiperList"></home-swiper>
    <home-icons :list="iconList"></home-icons>
    <home-recommend :list="recommendList"></home-recommend>
    <home-weekend :list="weekendList"></home-weekend>
  </div>
</template>

<script>
import HomeHeader from './components/Header.vue'
import HomeSwiper from './components/Swiper.vue'
import HomeIcons from './components/Icons.vue'
import HomeRecommend from './components/Recommend'
import HomeWeekend from './components/Weekend'
import axios from 'axios'
import { mapState } from 'vuex'
export default {
  name: 'Home',
  components: {
    HomeHeader,
    HomeSwiper,
    HomeIcons,
    HomeRecommend,
    HomeWeekend
  },
  data () {
    return {
      // 定义一个初始变量,用于比较变化与否
      lastCity: '',
      swiperList: [],
      iconList: [],
      recommendList: [],
      weekendList: []
    }
  },
  computed: {
    ...mapState(['city'])
  },
  methods: {
    getHomeInfo () {
      axios.get('/api/index.json?city=' + this.city).then(this.getHomeInfoSucc)
    },
    getHomeInfoSucc (res) {
      // console.log(res)
      res = res.data
      if (res.ret && res.data) {
        const data = res.data
        this.swiperList = data.swiperList
        this.iconList = data.iconList
        this.recommendList = data.recommendList
        this.weekendList = data.weekendList
      }
    }
  },
  mounted () {
    this.lastCity = this.city
    this.getHomeInfo()
  },
  activated () {
    if (this.lastCity !== this.city) {
      this.lastCity = this.city
      this.getHomeInfo()
    }
  }
}
</script>

<style>

</style>

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!