欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Vue中使用router.meta.keepAlive对页面进行缓存

程序员文章站 2022-03-04 17:40:34
...

需求:1. 从stockList页面到stockInfo页面,从stockInfo页面返回stockList,缓存stockList页面
           2. 从其他页面进入到stockList页面,则不缓存stockList页面


路由配置文件中:

{
  path: '/stockSelectionAndDiagnosticStocks',
  name: 'stockSelectionAndDiagnosticStocks',
  component: stockSelectionAndDiagnosticStocks,
  redirect: '/stockSelectionAndDiagnosticStocks/stockList',
  children: [
    {
      path: '/stockSelectionAndDiagnosticStocks/stockList',
      name: 'stockList',
      component: stockList,
      // 此处设置的原因:保证第一次从stockList进入到stockInfo中是缓存了的
      meta: { keepAlive: true }
    },
    {
      path: '/stockSelectionAndDiagnosticStocks/stockInfo',
      name: 'stockInfo',
      component: stockInfo
    }
  ]
}

App.vue中:

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

stockList.vue中:

beforeRouteLeave (to, from, next) {
  // 从列表页去到别的页面,如果不是详情页,则不缓存列表页
  if (to.name !== 'stockInfo') {
    this.$route.meta.keepAlive = false
  } else {
    this.$route.meta.keepAlive = true
  }
  next()
}