The keep-alive component is to realize that the page A from page B does not refresh, and other pages are refreshed when they enter page A

The keep-alive component is to realize that the page A from page B does not refresh, and other pages are refreshed when they enter page A

First, add an isBack field to the routing meta information meta of A to solve the problem that beforeRouterEnter cannot directly access the vue instance.

...
{
    
    
    path: '/A',//A页面
    name: 'A',
    component: List1,
    meta: {
    
    
        keepAlive: true, //此组件需要被缓存
        isBack: false
    }
},
{
    
    
    path: '/B',//B页面
    name: 'B',
    component: List2,
    meta: {
    
    
        keepAlive: true //此组件需要被缓存
    }
}
...

Use the beforeRouteEnter hook function to determine the source of the page:

beforeRouteEnter(to, from, next) {
    
    
  if(from.name === 'A') {
    
    
  //判断是从哪个路由过来的,若是detail页面不需要刷新获取新数据,
  //直接用之前缓存的数据即可
      to.meta.isBack = true;
  }
  next();
},

Need to use keep-alive to provide the hook function activated to complete whether to update:

activated() {
    
    
  if(!this.$route.meta.isBack) {
    
    
    // 如果isBack是false,表明需要获取新数据,否则就不再请求,直接使用缓存的数据
    Object.assign(this.$data, this.$options.data())//重置页面data里面所有变量
    this.getData(); // ajax获取数据方法
  }
  // 恢复成默认的false,避免isBack一直是true,导致下次无法获取数据
  this.$route.meta.isBack = false
},

Guess you like

Origin blog.csdn.net/qq_39367226/article/details/107451135