vue-使用keep-alive優化網頁性能


export default{
  name: 'Home',
  data () {
    return {
      iconList: [],
      recommendList: [],
      swiperList: [],
      weekendList: []
    }
  },
  components: {
    HomeHeader,
    HomeSwiper,
    HomeIcons,
    HomeRecommend,
    HomeWeekmend
  },
  methods: {
    getHomeInfo () {
      axios.get('/api/index.json')
        .then(this.getHomeInfoSucc)
    },
    getHomeInfoSucc (res) {
      if (res.data.ret && res.data.data) {
        const data = res.data.data
        this.iconList = data.iconList
        this.recommendList = data.recommendList
        this.swiperList = data.swiperList
        this.weekendList = data.weekendList
      }
    }
  },
  mounted () {
    this.getHomeInfo()
  }
}
</script>

每次從city頁切換回home頁面的時候mounted這個鈎子都會執行,ajax都會被重新獲取,性能需要優化。

用keep-alive,keep-alive是Vue的內置組件,能在組件切換過程中將狀態保留在內存中,防止重復渲染DOM。

app.vue

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

<script>
export default {
  name: 'App'
}
</script>

  keep-alive生命周期鈎子函數:activated、deactivated,使用<keep-alive>會將數據保留在內存中,如果要在每次進入頁面的時候獲取最新的數據,需要在activated階段獲取數據,承擔原來created鈎子中獲取數據的任務。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM