vue 2 keep-allive 缓存,activated和deactivated生命周期

373 阅读1分钟

keep-alive 包括被缓存的页面,例如A和B

使用场景需求

当A页面有查询条件,切换到B页面,A页面的查询条件还是存在,并且重新请求接口。

问题

keep-alive包括之后,是缓存了查询条件,但是,接口不会重新执行,以至于不能获取最新的数据

解决问题

第一种:

使用watch监听,如果是这个路由就调用接口

watch: {
    $route: function (to) {
      if (to.fullPath && !to.query.refresh) {
        if (to.fullPath == '路由连接') {
          this.getTableData()//调用接口
        }
      }
    }
  },

弊端:是会造成页面的压力,每个页面都要写这段代码,代码冗余

第二种:

在公共方法里面,找到页面调用表格的方法

 if (newRoute.meta.keepAlive) {
          if (that.$refs['rightContent'].$children[0].$children[0].$refs[newRoute.path.slice(1)]) {
            that.$refs['rightContent'].$children[0].$children[0].$refs[newRoute.path.slice(1)].$parent.getTableData()
          }
        }

弊端:层级太多,当是多级的菜单会找不到refs,无法调用方法

第三种:

使用activated和deactivated

image.png

activated() {
    // 在组件被激活后执行的代码
    console.log('组件被激活了')
    if ( this.$route.meta.keepAlive) {
      console.log('调用')
      this.getTableData()
    }
  },

当页面有缓存的时候,会去调用这个方法 问题:当刷新页面的时候,会调用两次接口,created和activated里面都会调用 解决问题:加个标识,在created里面设置为true,组件失活的时候,改为false,刷新页面只会调用一次。

data() {
    return {
        isCache: false
    }
}
created() {
    this.isCache = true;
    this.getTableData()
},
activated() {
    // 在组件被激活后执行的代码
    console.log('组件被激活了')
    if (this.isCache == false && this.$route.meta.keepAlive) {
      console.log('调用')
      this.getTableData()
    }
  },
  deactivated() {
    console.log('组件失活')
    this.isCache = false
  },

第四种

getMatchedComponents

const currentComponentInstance = router.getMatchedComponents(to)[3];
    if (currentComponentInstance && currentComponentInstance.methods && currentComponentInstance.methods.createAAA && typeof currentComponentInstance.methods.createAAA === 'function') {
        // 调用当前页面的 someMethod 方法
        currentComponentInstance.methods.createAAA();
    }

弊端:这个方法可以找到页面的方法,但是页面的data数据会出现找不到的情况 综上所述:建议使用第三种,虽然会在每个页面都要调用一次