【Vue.js】之keep-alive

keep-alive

  • 缓存组件
  • 频繁切换,不需要重复渲染
  • Vue常见性能优化

activated函数:keep-alive组件激活时调用

activated函数:keep-alive组件停用时调用

包裹动态组件时, 会缓存不活动的组件实例, 主要用于保留组件状态或避免重新渲染
例如有一个列表和一个详情, 那么用户就会经常执行打开详情 => 返回列表 => 打开详情…这样的话列表和详情都是频率很高的一个页面,就可以对列表组件使用进行缓存,这样用户每次返回列表的时候,都能从缓存中快速渲染而不是重新渲染。

代码实例-KeepAlive实现选项卡切换

KeepAlive.vue

<template>
  <div>
    <button @click="changeState('A')">A</button>
    <button @click="changeState('B')">B</button>
    <button @click="changeState('C')">C</button>

    <keep-alive>
      <!-- tab 切换 -->
      <KeepAliveStageA v-if="state === 'A'" />
      <!-- v-show -->
      <KeepAliveStageB v-if="state === 'B'" />
      <KeepAliveStageC v-if="state === 'C'" />
    </keep-alive>
  </div>
</template>

<script>
import KeepAliveStageA from './KeepAliveStateA'
import KeepAliveStageB from './KeepAliveStateB'
import KeepAliveStageC from './KeepAliveStateC'

export default {
  components: {
    KeepAliveStageA,
    KeepAliveStageB,
    KeepAliveStageC
  },
  data () {
    return {
      state: 'A'
    }
  },
  methods: {
    changeState (state) {
      this.state = state
    }
  }
}
</script>

KeepAliveStateA.vue

<template>
  <p>state A</p>
</template>

<script>
export default {
  mounted () {
    // eslint-disable-next-line
    console.log("A mounted");
  },
  destroyed () {
    // eslint-disable-next-line
    console.log("A destroyed");
  }
}
</script>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值