keep-alive活性组件

vue在页面切换的时候,会将原来的页面注销掉,然后渲染新的页面,看似一样,实则每次打开的都是新页面。性能不好,所以有了keepalive

  • 它拥有两个独有的生命周期钩子函数,分别为 activateddeactivated

  • keepalive包裹的组件不会销毁,而是会缓存在 deactivated 钩子函数中,根据缓存渲染后执行 activated 函数

示例:商品列表页到详情页,从详情页回到列表页的时候需要记录一些信息,比如下次在进来详情页直接无感定位到上次浏览的位置,这时就需要用到keepalive来做活性组件。如果回到列表页的时候需要实时刷新数据,那可以在 activated 钩子函数中请求数据,也可以在watch中监听路由的变化

<template>
  <div id="app">
    <button @click="currentTab = 'Home'">首页</button>
    <button @click="currentTab = 'About'">关于</button>

    <!-- 使用 keep-alive 包裹动态组件 -->
    <keep-alive>
      <component :is="currentTab"></component>
    </keep-alive>
  </div>
</template>

<script>
// 定义组件
const Home = {
  name: 'Home',
  data() {
    return {
      count: 0,
      timer: null
    }
  },
  template: `
    <div>
      <h2>首页</h2>
      <p>计数: {{ count }}</p>
      <button @click="count++">增加</button>
      <input v-model="message" placeholder="输入内容..." />
    </div>
  `,
  data() {
    return {
      count: 0,
      message: ''
    }
  },
  created() {
    console.log('Home 组件 created')
  },
  mounted() {
    console.log('Home 组件 mounted')
  },
  destroyed() {
    console.log('Home 组件 destroyed')
  },
  activated() {
    console.log('Home 组件 activated - 从缓存激活')
  },
  deactivated() {
    console.log('Home 组件 deactivated - 进入缓存')
  }
}

const About = {
  name: 'About',
  template: `
    <div>
      <h2>关于页面</h2>
      <p>这个组件也会被缓存</p>
    </div>
  `,
  created() {
    console.log('About 组件 created')
  }
}
export default {
  name: 'App',
  components: { Home, About },
  data() {
    return {
      currentTab: 'Home'
    }
  }
}
</script>
  • 条件缓存(include/exclude)
  • <template>
      <div>
        <!-- 只缓存 Home 和 About 组件 -->
        <keep-alive :include="['Home', 'About']">
          <component :is="currentComponent"></component>
        </keep-alive>
    
        <!-- 缓存除 User 外的所有组件 -->
        <keep-alive :exclude="['User']">
          <component :is="currentComponent"></component>
        </keep-alive>
    
        <!-- 使用正则表达式匹配 -->
        <keep-alive :include="/Home|About/">
          <component :is="currentComponent"></component>
        </keep-alive>
      </div>
    </template>
    
  • 最大缓存实例数(max):如果超出,最久没有被访问的缓存实例被销毁

  • <template>
      <div>
        <!-- 最多缓存 3 个组件实例,超出时销毁最久未使用的 -->
        <keep-alive :max="3">
          <router-view></router-view>
        </keep-alive>
      </div>
    </template>
    

results matching ""

    No results matching ""