vue的keep-alive理解

  • keep-alive是Vue的一个内置组件,使页面切换时可以将状态保留在内存中,或防止重复渲染DOM。
  • keep-alive组件有三个props include(符合要求的缓存)、exclude(符合要求的不缓存)、max(最多缓存的数量)
  • include、exclude可以是以逗号分割的字符串.数组。正则表达式
<!-- 逗号分隔字符串 -->
<template>
  <section class="app-main">
    <transition name="fade-transform" mode="out-in">
      <keep-alive :include="a,b">
        <router-view :key="$route.path" />
      </keep-alive>
    </transition>
  </section>
</template>

<!-- 正则表达式 (使用 `v-bind`) -->
<template>
  <section class="app-main">
    <transition name="fade-transform" mode="out-in">
      <keep-alive :include="/a|b/">
      	<component :is="view"></component>
	  </keep-alive>
    </transition>
  </section>
</template>

<!-- 数组 (使用 `v-bind`) -->
<template>
  <section class="app-main">
    <transition name="fade-transform" mode="out-in">
      <keep-alive :include="[a,b]">
        <router-view :key="$route.path" />
      </keep-alive>
    </transition>
  </section>
</template>
  • 匹配首先检查自身的name选项,其次匹配局部注册的名称(父组件 components 选项的键值)。匿名组件不能被匹配。
  • 被keep-alive包裹的页面,会多activated和deactivated两个钩子函数。
  • 首次进入组件钩子的执行函数 beforeRouteEnter ——》beforeCreate——》created——》beforeMount——》mounted——》activated ——》… ——》beforeRouteLeave ——》deactivated
  • 再次进入组件钩子执行顺序 beforeRouteEnter ——》activated ——》… ——》beforeRouteLeave ——》deactivated
  • 缓存后获取数据通过beforeRouteEnter和activated方法
// 方案1
// beforeRouteEnter 是支持给next传递回调的唯一守卫,回调的参数vm是当前vue实例。
beforeRouteEnter(to, from, next){
  next(vm=>{
      console.log(vm)
      // 每次进入路由执行
      vm.getData()  // 获取数据
  })
},
// 方案2
methods: {}
activated(){
 this.getData() // 获取数据
},
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值