美文网首页
vue中keep-alive 前进后退时页面数据缓存和刷新问题

vue中keep-alive 前进后退时页面数据缓存和刷新问题

作者: 放任自由f0 | 来源:发表于2019-10-15 17:23 被阅读0次

vue中keep-alive 前进后退时页面数据缓存和刷新问题

keep-alive用法:

1、在app.vue中定义keep-aliv

<router-view v-if="!$route.meta.keepAlive"></router-view>
<keep-alive>
     <router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive></pre>

2、在路由文件router.js中,定义meta信息

{
  path: '/space4',
  name: 'space4',
  component: () => import( './components/workspace/space4.vue'),
  meta: {
    isUseCache: false, // 默认不缓存
    keepAlive: true,
  }
}

3、列表页的activated钩子

activated() { if(!this.$route.meta.isUseCache){ //isUseCache 时添加中router中的元信息,判读是否要缓存
      this.contactList = [] //清空原有数据
      this.contactDisplay() // 重新加载
 }
  },
  methods: {
    onClickLeft() { this.$router.go(-1)
    },
    contactDisplay() { this.contactListGet = JSON.parse(sessionStorage.getItem('contact-item'))
      let personal = this.contactListGet
      let i = 0
      for(i in personal) { // let surname = personal[i].substring(0,1)
        let surname = personal[i].substring(personal[i].length-2) this.contactList.push({'surname': surname, name: personal[i]})
      }
      console.log('contactList', this.contactList)
    }
  }

4、详细页面 beforeRouteLeave的钩子函数

beforeRouteLeave(to, from, next){ // 列表页面跳转到 详情页时,设置需要缓存
    if(to.name=='spaceContact'){
      from.meta.isUseCache = true }
    next()
  }

vue钩子函数:

设置了keepAlive缓存的组件:

第一次进入:beforeRouterEnter ->created->…->activated->…->deactivated

后续进入时:beforeRouterEnter ->activated->deactivated 可以看出,只有第一次进入该组件时,才会走created钩子,而需要缓存的组件中activated是每次都会走的钩子函数。所以,我们要在这个钩子里面去判断,当前组件是需要使用缓存的数据还是重新刷新获取数据。

keep-alive生命周期钩子函数:activated、deactivated

使用<keep-alive>会将数据保留在内存中,如果要在每次进入页面的时候获取最新的数据,需要在activated阶段获取数据,承担原来created钩子中获取数据的任务。

被包含在 <keep-alive> 中创建的组件,会多出两个生命周期的钩子: activated 与 deactivated

activated:在组件被激活时调用,在组件第一次渲染时也会被调用,之后每次keep-alive激活时被调用。

deactivated:在组件被停用时调用。

相关文章

网友评论

      本文标题:vue中keep-alive 前进后退时页面数据缓存和刷新问题

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