vue基础之keep-alvie保持历史页面数据不变,切换页面后数据不变keep-alvie

1:路由配置文件设置

{
      path: '/MenuM',
      component: Layout,
      redirect: '/MenuM',
      children: [
        {
          path: 'MenuM',
          name: 'MenuM',
          component: () => import('@/views/MenuM'),
          meta: { title: '主界面', icon: 'table', keepAlive: true }
        }
      ]
    },

2.标注需要缓存的组件,用包裹

这一步需要注意了,有的是在APP.VUE改,有的要看所在组件里改哦~~,比如上面的component: Layout,

那我们需要修改的文件就不是app.vue了,需要修改对应文件才行,
要不然就会无法缓存页面数据,出现问题
src\layout\components\AppMain.vue

<template>
  <section class="app-main">
    <div class="app-main-top">
      <transition name="fade-transform" mode="out-in">
        <div>
          <keep-alive>
            <router-view v-if="$route.meta.keepAlive" :key="key"></router-view>
          </keep-alive>
          <router-view v-if="!$route.meta.keepAlive" :key="key"></router-view>
          <!-- <router-view :key="key" /> -->
        </div>
      </transition>
    </div>
  </section>
</template>

<script>
export default {
  name: 'AppMain',
  computed: {
    key() {
      return this.$route.path
    }
  }
}
</script>

<style lang="less" scoped>
.app-main {
  /*50 = navbar  */
  min-height: calc(100vh - 50px);
  width: 100%;
  position: relative;
  overflow: hidden;
  // background-image: url(~@/assets/image/bg01.jpg);
  .app-main-top {
    padding-top: 5px;
    padding-bottom: 5px;
    // background: rgba(255, 255, 255, 0.9);
    background: rgba(255, 255, 255, 1); // 修改背景
    min-height: calc(100vh - 50px);
  }
}
.fixed-header + .app-main {
  padding-top: 50px;
}
</style>

<style lang="scss">
// fix css style bug in open el-dialog
.el-popup-parent--hidden {
  .fixed-header {
    padding-right: 15px;
  }
}
</style>

在router中设置需要缓存的组件
包裹需要缓存组件
页面第一次进入,钩子的触发顺序created-> mounted-> activated,退出时触发deactivated。当再次进入(前进或者后退)时,只触发activated
可以动态控制是否缓存组件,代码如下:

beforeRouteLeave(to, from, next) {
  // 设置下一个路由的 meta
  to.meta.keepAlive = false; // 不缓存,即刷新
  next();
}

参考来源
https://www.jianshu.com/p/eeda81293826
https://zhuanlan.zhihu.com/p/48628352

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值