zoukankan      html  css  js  c++  java
  • 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>

    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是每次都会走的钩子函数。所以,我们要在这个钩子里面去判断,当前组件是需要使用缓存的数据还是重新刷新获取数据。

    【参考文章】

  • 相关阅读:
    CF1458D
    CF1415F
    CF612F
    部分博客请移步Gitbub
    Vlc视频插件遮挡弹出框
    kubernetes容器编排YAML详解
    Kubernetes核心技术之Pod
    Kubeadm搭建K8S集群
    博客配套工程公开
    Modelsim联合Matlab搭建FPGA图像仿真平台
  • 原文地址:https://www.cnblogs.com/miny-simp/p/11345535.html
Copyright © 2011-2022 走看看