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

需求: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()
}

*** 增加需求:从stockInfo页面通过“特殊的”点击事件回到stockList,stockList页面的列表需要按照字段更新 ***

stockInfo.vue中:(其中setStore、getStore是封装的sessionStorage)

clickHistoryItem (val) {
  setStore('searchName', val)
  this.$router.push({ name: 'stockList' })
}

stockList.vue中:

// 只有当缓存的情况写才触发这两个钩子函数
activated () {
  if (getStore('searchName')) {
    this.pageIndex = 1
    this.searchStockFirstStep(getStore('searchName'))
  }
},
deactivated () {
  removeStore('searchName')
}

 

  • 11
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值