vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Vue3中keep-alive的使用

Vue3中keep-alive的使用及注意事项说明

作者:大樊子

这篇文章主要介绍了Vue3中keep-alive的使用及注意事项说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

Vue3中keep-alive使用及注意事项

keep-alive 是 Vue 内置的一个抽象组件,用于缓存不活动的组件实例,避免重复渲染,提高性能。

以下是它的详细用法和注意事项:

基本用法

<template>
  <!-- 基本用法 -->
  <keep-alive>
    <component :is="currentComponent"></component>
  </keep-alive>

  <!-- 缓存特定组件 -->
  <keep-alive include="CompA,CompB" exclude="CompC">
    <router-view></router-view>
  </keep-alive>
</template>

主要功能

核心属性

生命周期钩子

keep-alive 缓存的组件会触发特有的生命周期钩子:

import { onActivated, onDeactivated } from 'vue'

export default {
  setup() {
    onActivated(() => {
      console.log('组件被激活')
    })
    
    onDeactivated(() => {
      console.log('组件被停用')
    })
  }
}

与 Vue Router 结合使用

<template>
  <keep-alive :include="cachedViews">
    <router-view v-slot="{ Component }">
      <transition name="fade">
        <component :is="Component" />
      </transition>
    </router-view>
  </keep-alive>
</template>

<script>
import { ref } from 'vue'
export default {
  setup() {
    const cachedViews = ref(['Home', 'User'])
    return { cachedViews }
  }
}
</script>

注意事项

组件必须有 name 选项includeexclude 匹配的是组件的 name 选项

动态组件切换问题

<keep-alive><comp :key="id"></comp></keep-alive>
<comp v-if="show"></comp>

内存占用

数据更新时机

滚动行为

onActivated(() => {
  window.scrollTo(0, 0)
})

与 Transition 一起使用

<router-view v-slot="{ Component }">
  <transition name="fade">
    <keep-alive>
      <component :is="Component" />
    </keep-alive>
  </transition>
</router-view>

最佳实践

const routes = [
  {
    path: '/user',
    component: User,
    meta: { keepAlive: true }
  }
]

通过合理使用 keep-alive,可以显著提升应用性能,特别是在移动端或需要频繁切换视图的场景中。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文