美文网首页
Vue项目 --- keep-alive

Vue项目 --- keep-alive

作者: V火力全开 | 来源:发表于2018-07-16 14:53 被阅读0次

keep-alive是Vue的内置组件,能在组件切换过程中将状态保留在内存中,防止重复渲染DOM。

使用示例:

<template>
  <div id="app">
    <keep-alive>
      <!--显示的是当前路由地址所对应的内容-->
      <router-view/>
    </keep-alive>
  </div>
</template>

路由中的内容被加载过一次后,就会把路由中的内容放在内存中,下次再进这个路由,不需要重新渲染组件。

当使用keep-alive组件的时候,会多出2个生命周期的方法activateddeactivated,当页面重新显示的时候会调用activated,我们可以在这个方法中做判断,是否使用内存中的内容。

例如:

methods: {
    getHomeInfo () {
      axios.get('/api/index.json?city=' + this.city)
        .then(this.getHomeInfoSucc)
    },
    getHomeInfoSucc (res) {
    }
  },
activated () {
    if (this.lastCity !== this.city) {
      this.lastCity = this.city
      this.getHomeInfo()
    }
  }

相关文章

网友评论

      本文标题:Vue项目 --- keep-alive

      本文链接:https://www.haomeiwen.com/subject/kskbpftx.html