Vue2.5 旅游项目实例18 城市选择页-使用keep-alive优化网页性能

创建分支:city-keepalive

拉取并切换分支:

git pull
git checkout city-keepalive

启动服务,点击右上角的城市进入城市列表页,点击城市再返回到首页,这一系列操作下来,我们在Network里会发现不停的请求 indes.json 和 city.json ,这样性能会降低

如何进行优化?

打开App.vue文件:

<template>
  <div id="app">
    <keep-alive>
      <router-view/>
    </keep-alive>
  </div>
</template>

keep-alive这个是Vue自带的标签,意思是:路由的内容被加载过一次之后,就把路由中的内容放到内存之中,下次在进这个路由的时候,不需要去重新渲染这个组件去重新执行钩子函数,只需要从内存中把以前存储的内容拿出来显示到页面中就可以了。

还有个问题,就是在城市列表页中点击切换城市后,回到首页,首页的数据应该重新请求为相应城市的数据。

打开Home.vue文件:

<script>
import { mapState } from 'vuex'
export default {
  computed: {
    ...mapState(['city'])
  },
  methods: {
    getHomeInfo () {
      axios.get('/api/index.json?city=' + this.city).then(this.getHomeInfoSucc)
    }
  }
}
</script>

然后切换城市后需要重新发起请求,定义一个lastCity变量:

当用 keepalive 的时候,会多出一个生命周期函数 activated

export default {
  data () {
    return {
      lastCity: ''
    }
  },
  mounted () {
    this.lastCity = this.city
    this.getHomeInfo()
  },
  // 当用 keepalive 的时候,会多出一个生命周期函数 activated
  activated () {
    if (this.lastCity !== this.city) {
      this.lastCity = this.city
      this.getHomeInfo()
    }
  },
}

当上次城市与当前城市不一致时,在此发起ajax请求,并把当前城市存储到上次城市中。而城市列表不管点开多少次,也只发起一次ajax请求。

下面提交代码:

git add .
git commit -m "keepalive优化"
git push

git checkout master
git merge city-keepalive
git push
原文地址:https://www.cnblogs.com/joe235/p/12503985.html