加入KeepAlive 让你的项目体验更良好

383 阅读19分钟

在现代前端开发中,用户体验是一个至关重要的因素。特别是在使用 Vue.js 等框架构建单页应用时,组件的切换效率直接影响到用户的使用感受。今天,我们将深入探讨 Vue 的 KeepAlive 特性,了解它为何如此重要,以及如何在实际项目中有效运用。

什么是 KeepAlive?

KeepAlive 是 Vue.js 提供的一个内置组件,用于缓存组件的状态。当我们在组件之间切换时,使用 KeepAlive 可以避免频繁的卸载和挂载,从而提高性能和用户体验。

今天主要通过一个tab 体验KeepAlive 好处。我们先来写一个不使用KeepAlive 的tab案例。这个案例主要展示不同新闻类型的数据。我们分别在tab内容组件中的onMounted , onUnmounted中分别打印一句话。

编写4个tab 内容组件:

国内类型组件:

<template>
  <div class="list">
    <ul>
      <li v-for="item in data" :key="item.uniquekey">
        <a :href="item.url">{{ item.title }}</a>
        <span>{{ item.time }}</span>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted } from 'vue'
const data = [
        {
            "uniquekey": "9cf9812e71720ca7990be9b16550eb22",
            "title": "(新春走基层)广东英德:“剥皮黄金”麻竹笋 成就百亿富民产业",
            "date": "2025-02-13 13:46:00",
            "category": "国内",
            "author_name": "国际时事讲解",
            "url": "https://mini.eastday.com/mobile/250213134628865170379.html",
            "thumbnail_pic_s": "",
            "is_content": "1"
        },
        {
            "uniquekey": "ee7c92db8b523add74d4cf7f03733b78",
            "title": "关注亚冬会|“双金王”李磊回家!",
            "date": "2025-02-13 13:44:00",
            "category": "国内",
            "author_name": "中国吉林网",
            "url": "https://mini.eastday.com/mobile/250213134431107745287.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/news/20250213/20250213134431_e0592fabfb4c522ec8f113870a776921_1_mwpm_03201609.jpeg",
            "thumbnail_pic_s02": "https://dfzximg02.dftoutiao.com/news/20250213/20250213134431_e0592fabfb4c522ec8f113870a776921_2_mwpm_03201609.jpeg",
            "thumbnail_pic_s03": "https://dfzximg02.dftoutiao.com/news/20250213/20250213134431_e0592fabfb4c522ec8f113870a776921_3_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "f51b3597061ced9e336931c91a669bda",
            "title": "每日一图|高铁列车上的喜乐元宵节",
            "date": "2025-02-13 13:35:00",
            "category": "国内",
            "author_name": "人民网-浙江频道,供稿:人民资讯",
            "url": "https://mini.eastday.com/mobile/250213133541899920131.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/news/20250213/20250213133541_cf2a9da3b57cd17edbf79c61b9782e7a_1_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "7b3abb0963d60d4309cd798c5488fb44",
            "title": "花灯映彩闹元宵 汤圆暖心医患情",
            "date": "2025-02-13 13:35:00",
            "category": "国内",
            "author_name": "大众报业·齐鲁壹点",
            "url": "https://mini.eastday.com/mobile/250213133502991132413.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/news/20250213/20250213133502_23d84fb71ca40059cec5aff7d130882b_1_mwpm_03201609.jpeg",
            "thumbnail_pic_s02": "https://dfzximg02.dftoutiao.com/news/20250213/20250213133502_23d84fb71ca40059cec5aff7d130882b_2_mwpm_03201609.jpeg",
            "thumbnail_pic_s03": "https://dfzximg02.dftoutiao.com/news/20250213/20250213133502_23d84fb71ca40059cec5aff7d130882b_3_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "2c9cc4d521016488245155934bb34be6",
            "title": "2025年元宵节无人机编队表演及焰火晚会在延吉举行",
            "date": "2025-02-13 13:23:00",
            "category": "国内",
            "author_name": "中国网",
            "url": "https://mini.eastday.com/mobile/250213132315265717360.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/news/20250213/20250213132315_bbfb4bedc6150bb4803534fac90c9766_1_mwpm_03201609.jpeg",
            "thumbnail_pic_s02": "https://dfzximg02.dftoutiao.com/news/20250213/20250213132315_bbfb4bedc6150bb4803534fac90c9766_2_mwpm_03201609.jpeg",
            "thumbnail_pic_s03": "https://dfzximg02.dftoutiao.com/news/20250213/20250213132315_bbfb4bedc6150bb4803534fac90c9766_3_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "a557d47bc6664ab807326e99375a65e3",
            "title": "安图:正月十五喜庆多闹吃闹玩闹元宵",
            "date": "2025-02-13 13:22:00",
            "category": "国内",
            "author_name": "中国网",
            "url": "https://mini.eastday.com/mobile/250213132235425945544.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/news/20250213/20250213132235_6834ee79f162f532eb68f68fd3c296a0_1_mwpm_03201609.jpeg",
            "thumbnail_pic_s02": "https://dfzximg02.dftoutiao.com/news/20250213/20250213132235_6834ee79f162f532eb68f68fd3c296a0_2_mwpm_03201609.jpeg",
            "thumbnail_pic_s03": "https://dfzximg02.dftoutiao.com/news/20250213/20250213132235_6834ee79f162f532eb68f68fd3c296a0_3_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "d10f2ed7986cdef22475e2c7dd6e6545",
            "title": "南北冰雪同热 产业消费共兴",
            "date": "2025-02-13 13:16:00",
            "category": "国内",
            "author_name": "国际时事讲解",
            "url": "https://mini.eastday.com/mobile/250213131623545502073.html",
            "thumbnail_pic_s": "",
            "is_content": "1"
        },
        {
            "uniquekey": "b28eee2f134844f7f028990af13c2ab6",
            "title": "“我们的节日·欢乐中国年”系列活动点亮我省各地节日氛围",
            "date": "2025-02-13 13:11:00",
            "category": "国内",
            "author_name": "中国吉林网",
            "url": "https://mini.eastday.com/mobile/250213131144518800976.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/news/20250213/20250213131144_5e91a6372432317a98fe5b589187badf_1_mwpm_03201609.jpeg",
            "thumbnail_pic_s02": "https://dfzximg02.dftoutiao.com/news/20250213/20250213131144_5e91a6372432317a98fe5b589187badf_2_mwpm_03201609.jpeg",
            "thumbnail_pic_s03": "https://dfzximg02.dftoutiao.com/news/20250213/20250213131144_5e91a6372432317a98fe5b589187badf_3_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "e7097be025cd728aed6ffd7b7776a474",
            "title": "东湖评论:让“惟楚有材”在支点建设中绽放时代光芒",
            "date": "2025-02-13 13:09:00",
            "category": "国内",
            "author_name": "荆楚网 (湖北日报网)",
            "url": "https://mini.eastday.com/mobile/250213130928881466108.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/news/20250213/20250213130928_4e668e852205d21f7d96890b5a9ebe57_1_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "47c8fe4be97a2bc58cfbae8519010a54",
            "title": "东湖评论:着力培养创新人才 加快实现“支点建设”的整体提升",
            "date": "2025-02-13 13:09:00",
            "category": "国内",
            "author_name": "荆楚网 (湖北日报网)",
            "url": "https://mini.eastday.com/mobile/250213130920988507339.html",
            "thumbnail_pic_s": "",
            "is_content": "1"
        }
    ]

onMounted(() => {
  console.log('国内新闻组件挂载')
})
onUnmounted(() => {
  console.log('国内新闻组件卸载')
})

  
</script>

<style lang="scss" scoped>
.list {
  height: 355px;
  overflow-y: auto;
}
.list ul{
  padding-left: 20px;

  li {
    padding: 10px 0;
    display: flex;
    justify-content: space-between;

    a {
      width: calc(100% - 80px);
      text-decoration: none;
      font-size: 18px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      color: #333;
    }
  }
}
</style>

国际类型组件:

<template>
  <div class="list">
    <ul>
      <li v-for="item in data" :key="item.uniquekey">
        <a :href="item.url">{{ item.title }}</a>
        <span>{{ item.time }}</span>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted } from 'vue'
const data = [
        {
            "uniquekey": "6160a21d6a584f3b20a405410b389476",
            "title": "墨西哥将就美加征钢铝关税问题向白宫发函",
            "date": "2025-02-13 13:41:00",
            "category": "国际",
            "author_name": "国际时事讲解",
            "url": "https://mini.eastday.com/mobile/250213134128526882937.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/minimodify/20250213/690x388_67ad8539c455b_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "108f5210aa47c2431c1bd444a723aed4",
            "title": "尹锡悦出席弹劾案庭审第八场公开辩论,3名证人将接受问讯",
            "date": "2025-02-13 13:41:00",
            "category": "国际",
            "author_name": "国际时事讲解",
            "url": "https://mini.eastday.com/mobile/250213134103053602666.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/minimodify/20250213/690x388_67ad850e4a63e_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "2bd0df2ffa74dac32ecc70e84d0c2a4f",
            "title": "法国东南部城市一酒吧发生手雷爆炸事件,致12人受伤",
            "date": "2025-02-13 13:34:00",
            "category": "国际",
            "author_name": "国际时事讲解",
            "url": "https://mini.eastday.com/mobile/250213133426392951201.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/minimodify/20250213/690x388_67ad83817f680_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "6337bc267db298a1466d2730cc08716e",
            "title": "韩国一渔船发生火灾,5人获救、6人情况不明",
            "date": "2025-02-13 13:30:00",
            "category": "国际",
            "author_name": "国际时事讲解",
            "url": "https://mini.eastday.com/mobile/250213133034785864866.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/minimodify/20250213/690x388_67ad829a1705d_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "3a4715f5ad757e9be5e11c63dffe65c6",
            "title": "234人受害!韩国破获网络性剥削大案",
            "date": "2025-02-13 13:29:00",
            "category": "国际",
            "author_name": "国际时事讲解",
            "url": "https://mini.eastday.com/mobile/250213132916989742576.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/minimodify/20250213/690x388_67ad8276c768d_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "9681518e621c8f068f0f6b78ce7db39c",
            "title": "在凌晨4点舔醒富豪,是最隐秘的人肉闹钟生意",
            "date": "2025-02-13 13:19:00",
            "category": "国际",
            "author_name": "国际时事讲解",
            "url": "https://mini.eastday.com/mobile/250213131958972274791.html",
            "thumbnail_pic_s": "",
            "is_content": "1"
        },
        {
            "uniquekey": "d89bf230ddef0a01c9d4908c5af25951",
            "title": "苏丹西部两村庄遭武装分子袭击,造成18人死亡",
            "date": "2025-02-13 13:16:00",
            "category": "国际",
            "author_name": "中国新闻网",
            "url": "https://mini.eastday.com/mobile/250213131623201591235.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/minimodify/20250213/690x388_67ad87f9cb6da_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "7dc8a7b6358f0f5a53907d55d380a61a",
            "title": "23岁中国女留学生在美遇害 曾有男子从其卧室窗户爬出",
            "date": "2025-02-13 12:46:00",
            "category": "国际",
            "author_name": "知世",
            "url": "https://mini.eastday.com/mobile/250213124610540117863.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/news/20250213/20250213124610_f933da9e900d7f6b39236f84d0cda827_1_mwpm_03201609.jpeg",
            "thumbnail_pic_s02": "https://dfzximg02.dftoutiao.com/news/20250213/20250213124610_f933da9e900d7f6b39236f84d0cda827_2_mwpm_03201609.jpeg",
            "thumbnail_pic_s03": "https://dfzximg02.dftoutiao.com/news/20250213/20250213124610_f933da9e900d7f6b39236f84d0cda827_3_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "dd9d2c9bf667fc1fe087a5a6037fc608",
            "title": "泰国国家旅游局:2月抵泰中国游客预计减少7%",
            "date": "2025-02-13 11:49:00",
            "category": "国际",
            "author_name": "国际时事讲解",
            "url": "https://mini.eastday.com/mobile/250213114931551131153.html",
            "thumbnail_pic_s": "",
            "is_content": "1"
        },
        {
            "uniquekey": "07dc89c14b78ae8b6a8c0a1468d49da5",
            "title": "奥地利自由党组阁失败",
            "date": "2025-02-13 11:46:00",
            "category": "国际",
            "author_name": "国际时事讲解",
            "url": "https://mini.eastday.com/mobile/250213114607289685055.html",
            "thumbnail_pic_s": "",
            "is_content": "1"
        }
    ]
onMounted(() => {
  console.log('国际新闻组件挂载')
})
onUnmounted(() => {
  console.log('国际新闻组件卸载')
})
</script>

<style lang="scss" scoped>
.list {
  height: 355px;
  overflow-y: auto;
}
.list ul{
  padding-left: 20px;

  li {
    padding: 10px 0;
    display: flex;
    justify-content: space-between;

    a {
      width: calc(100% - 80px);
      text-decoration: none;
      font-size: 18px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      color: #333;
    }
  }
}
</style>

军事类型组件

<template>
  <div class="list">
    <ul>
      <li v-for="item in data" :key="item.uniquekey">
        <a :href="item.url">{{ item.title }}</a>
        <span>{{ item.time }}</span>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted } from 'vue'
const data = [
        {
            "uniquekey": "ff748f99631dafc66faaa92f443c9540",
            "title": "苏丹冲突双方在西部扎姆扎姆难民营交火",
            "date": "2025-02-12 16:49:00",
            "category": "军事",
            "author_name": "国际时事讲解",
            "url": "https://mini.eastday.com/mobile/250212164921624346846.html",
            "thumbnail_pic_s": "",
            "is_content": "1"
        },
        {
            "uniquekey": "bfd140d0589bb17d6445ea44ee547288",
            "title": "视频公布!东部战区位台岛周边战备警巡,解放军喊话台舰",
            "date": "2025-02-12 16:42:00",
            "category": "军事",
            "author_name": "杭州网",
            "url": "https://mini.eastday.com/mobile/250212164253421869562.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/news/20250212/20250212164253_91dcc5fc393a1239f8a5feae292daac2_1_mwpm_03201609.jpeg",
            "thumbnail_pic_s02": "https://dfzximg02.dftoutiao.com/news/20250212/20250212164253_91dcc5fc393a1239f8a5feae292daac2_2_mwpm_03201609.jpeg",
            "thumbnail_pic_s03": "https://dfzximg02.dftoutiao.com/news/20250212/20250212164253_91dcc5fc393a1239f8a5feae292daac2_3_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "0fc8003c3b5bafd41ad6b255e4917340",
            "title": "中方敦促美日立即停止干涉中国内政,停止操弄涉华议题",
            "date": "2025-02-12 16:41:00",
            "category": "军事",
            "author_name": "锋行天下",
            "url": "https://mini.eastday.com/mobile/250212164159642718783.html",
            "thumbnail_pic_s": "",
            "is_content": "1"
        },
        {
            "uniquekey": "7c84a1b80bf65152cd164e8029acb988",
            "title": "美舰船过航台湾海峡 中国外交部回应",
            "date": "2025-02-12 16:11:00",
            "category": "军事",
            "author_name": "锋行天下",
            "url": "https://mini.eastday.com/mobile/250212161152987775389.html",
            "thumbnail_pic_s": "",
            "is_content": "1"
        },
        {
            "uniquekey": "3dfff11389d0cafe086c00eada52883e",
            "title": "中方:菲方配合美方引入“堤丰” 是害人害己之举",
            "date": "2025-02-12 16:11:00",
            "category": "军事",
            "author_name": "锋行天下",
            "url": "https://mini.eastday.com/mobile/250212161152850412615.html",
            "thumbnail_pic_s": "",
            "is_content": "1"
        },
        {
            "uniquekey": "1f34a29fc2cd776d329b7d76256338f5",
            "title": "人勤春来早 开工干劲足丨今年将保持高密度发射 航空航天人都有哪些心愿?",
            "date": "2025-02-12 16:11:00",
            "category": "军事",
            "author_name": "锋行天下",
            "url": "https://mini.eastday.com/mobile/250212161148953644508.html",
            "thumbnail_pic_s": "",
            "is_content": "1"
        },
        {
            "uniquekey": "0f0787d9b13b9d97074ad6468ad26beb",
            "title": "比武竞赛中拿佳绩,巢湖一现役军人荣获二等功",
            "date": "2025-02-12 13:13:00",
            "category": "军事",
            "author_name": "大皖新闻",
            "url": "https://mini.eastday.com/mobile/250212131343995761537.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/news/20250212/20250212131343_35557decec7ea563e0d55ca63bfe706a_1_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "cc09bfc24ccf9d03e6d5694c4825526d",
            "title": "新一代运载火箭家族再添新丁!飞行得又稳又准长八甲是怎么做到的?",
            "date": "2025-02-12 12:40:00",
            "category": "军事",
            "author_name": "锋行天下",
            "url": "https://mini.eastday.com/mobile/250212124049683882660.html",
            "thumbnail_pic_s": "",
            "is_content": "1"
        },
        {
            "uniquekey": "1ebcb873d25c68953ce816cfd5b0e8d1",
            "title": "京杭运河最大尺寸LNG动力内河集装箱运输船开启首航",
            "date": "2025-02-12 12:28:00",
            "category": "军事",
            "author_name": "大众网",
            "url": "https://mini.eastday.com/mobile/250212122809430934816.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/news/20250212/20250212122809_9dd8f441f49b244131ee260668f97e31_1_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "4a23c4bb51987c8dbf4a34bf8f28a744",
            "title": "探秘神奇的药石 山师附小五(5)中队参加“石头也能治病”科普活动",
            "date": "2025-02-12 11:42:00",
            "category": "军事",
            "author_name": "大众网",
            "url": "https://mini.eastday.com/mobile/250212114212356784754.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/news/20250212/20250212114212_95807e0e5bf3f17a4a0fc1869fbd97a8_1_mwpm_03201609.jpeg",
            "thumbnail_pic_s02": "https://dfzximg02.dftoutiao.com/news/20250212/20250212114212_95807e0e5bf3f17a4a0fc1869fbd97a8_2_mwpm_03201609.jpeg",
            "is_content": "1"
        }
    ]
onMounted(() => {
  console.log('军事新闻组件挂载')
})
onUnmounted(() => {
  console.log('军事新闻组件卸载')
})
</script>

<style lang="scss" scoped>
.list {
  height: 355px;
  overflow-y: auto;
}
.list ul{
  padding-left: 20px;

  li {
    padding: 10px 0;
    display: flex;
    justify-content: space-between;

    a {
      width: calc(100% - 80px);
      text-decoration: none;
      font-size: 18px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      color: #333;
    }
  }
}
</style>

娱乐类型组件

<template>
  <div class="list">
    <ul>
      <li v-for="item in data" :key="item.uniquekey">
        <a :href="item.url">{{ item.title }}</a>
        <span>{{ item.time }}</span>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted } from 'vue'
const data = [
        {
            "uniquekey": "1dac22bfe4052cff141d9b13306b4f04",
            "title": "哪吒二里李靖他们没说要为陈塘关百姓报仇,这个剧情设置合理吗?",
            "date": "2025-02-13 13:38:00",
            "category": "娱乐",
            "author_name": "大叔谈娱乐",
            "url": "https://mini.eastday.com/mobile/250213133838459462310.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/news/20250213/20250213133838_bef2ebce1a0ab30702b4f2815b5c5086_1_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "8f10f094319188dee75da9e17161fdd6",
            "title": "拿腔捏调,满脸疲惫,放大镜看《掌心》,复仇剧这样拍何愁没观众",
            "date": "2025-02-13 13:38:00",
            "category": "娱乐",
            "author_name": "大叔谈娱乐",
            "url": "https://mini.eastday.com/mobile/250213133810024750693.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/news/20250213/20250213133810_d680410381bb4a21770164ef8dd8be1c_1_mwpm_03201609.jpeg",
            "thumbnail_pic_s02": "https://dfzximg02.dftoutiao.com/news/20250213/20250213133810_d680410381bb4a21770164ef8dd8be1c_2_mwpm_03201609.jpeg",
            "thumbnail_pic_s03": "https://dfzximg02.dftoutiao.com/news/20250213/20250213133810_d680410381bb4a21770164ef8dd8be1c_3_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "8181df24e9a4436dcbdeca56c3e373ac",
            "title": "《花样年华》首映,《繁花》组队见证王家卫藏了25年的秘密",
            "date": "2025-02-13 13:37:00",
            "category": "娱乐",
            "author_name": "大叔谈娱乐",
            "url": "https://mini.eastday.com/mobile/250213133752545335713.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/news/20250213/20250213133752_0da2e86db42bb04f10264e2c4546de5c_1_mwpm_03201609.jpeg",
            "thumbnail_pic_s02": "https://dfzximg02.dftoutiao.com/news/20250213/20250213133752_0da2e86db42bb04f10264e2c4546de5c_2_mwpm_03201609.jpeg",
            "thumbnail_pic_s03": "https://dfzximg02.dftoutiao.com/news/20250213/20250213133752_0da2e86db42bb04f10264e2c4546de5c_3_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "4ca2902f792c920d69f04fbd523042d0",
            "title": "要不是陈塘关被屠城,申公豹永不知能力那么低的太乙真人为何受宠",
            "date": "2025-02-13 13:36:00",
            "category": "娱乐",
            "author_name": "大叔谈娱乐",
            "url": "https://mini.eastday.com/mobile/250213133605058162140.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/news/20250213/20250213133605_3c5b9022aef3773e2e69ee6f62fa3684_1_mwpm_03201609.jpeg",
            "thumbnail_pic_s02": "https://dfzximg02.dftoutiao.com/news/20250213/20250213133605_3c5b9022aef3773e2e69ee6f62fa3684_2_mwpm_03201609.jpeg",
            "thumbnail_pic_s03": "https://dfzximg02.dftoutiao.com/news/20250213/20250213133605_3c5b9022aef3773e2e69ee6f62fa3684_3_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "185241c7f1c5b4c3ddfa9844f60a9a08",
            "title": "元宵晚会收视出炉!最高突破11%,撒贝宁和机器人表演成最大惊喜",
            "date": "2025-02-13 13:35:00",
            "category": "娱乐",
            "author_name": "大叔谈娱乐",
            "url": "https://mini.eastday.com/mobile/250213133525448885859.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/news/20250213/20250213133525_a073d5efdd0deadccae6e9527735a1ce_2_mwpm_03201609.jpeg",
            "thumbnail_pic_s02": "https://dfzximg02.dftoutiao.com/news/20250213/20250213133525_a073d5efdd0deadccae6e9527735a1ce_3_mwpm_03201609.jpeg",
            "thumbnail_pic_s03": "https://dfzximg02.dftoutiao.com/news/20250213/20250213133525_a073d5efdd0deadccae6e9527735a1ce_4_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "c3ced5615bc8954fc33d08f6f2f64b41",
            "title": "电视剧《大明王朝1566》中的哪个配角最出色?为什么?",
            "date": "2025-02-13 13:34:00",
            "category": "娱乐",
            "author_name": "大叔谈娱乐",
            "url": "https://mini.eastday.com/mobile/250213133418953596494.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/news/20250213/20250213133418_b164549b74c277790d6d6fa0fd1fad07_1_mwpm_03201609.jpeg",
            "thumbnail_pic_s02": "https://dfzximg02.dftoutiao.com/news/20250213/20250213133418_b164549b74c277790d6d6fa0fd1fad07_2_mwpm_03201609.jpeg",
            "thumbnail_pic_s03": "https://dfzximg02.dftoutiao.com/news/20250213/20250213133418_b164549b74c277790d6d6fa0fd1fad07_3_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "42e846a0a8786ce28b86c1cc0ca097dd",
            "title": "第二十届巴拿马世博会巴拿马春晚落幕 酱中圣·武强年画·双获金",
            "date": "2025-02-13 13:26:00",
            "category": "娱乐",
            "author_name": "前沿观注",
            "url": "https://mini.eastday.com/mobile/250213132604678229241.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/minimodify/20250213/871x1433_67ad8188db0bd_mwpm_03201609.jpeg",
            "thumbnail_pic_s02": "https://dfzximg02.dftoutiao.com/minimodify/20250213/1234x585_67ad8189d86a0_mwpm_03201609.jpeg",
            "thumbnail_pic_s03": "https://dfzximg02.dftoutiao.com/minimodify/20250213/1230x641_67ad818a83de0_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "4b9a51d97e2f316c364d522086efe14a",
            "title": "霍启刚元宵节扭秧歌,和郭晶晶及子女二刷东北,晒全家滑雪视频",
            "date": "2025-02-13 13:21:00",
            "category": "娱乐",
            "author_name": "大叔谈娱乐",
            "url": "https://mini.eastday.com/mobile/250213132107348154931.html",
            "thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/news/20250213/20250213132107_27f7904d15da1e0e24e35645faa6a44f_1_mwpm_03201609.jpeg",
            "thumbnail_pic_s02": "https://dfzximg02.dftoutiao.com/news/20250213/20250213132107_27f7904d15da1e0e24e35645faa6a44f_2_mwpm_03201609.jpeg",
            "thumbnail_pic_s03": "https://dfzximg02.dftoutiao.com/news/20250213/20250213132107_27f7904d15da1e0e24e35645faa6a44f_3_mwpm_03201609.jpeg",
            "is_content": "1"
        },
        {
            "uniquekey": "810dfaad9bb404a0785d5f833060e91d",
            "title": "【地评线】东湖评论:《哪吒2》破圈,中国故事何以“圈粉”全球?",
            "date": "2025-02-13 13:09:00",
            "category": "娱乐",
            "author_name": "荆楚网 (湖北日报网)",
            "url": "https://mini.eastday.com/mobile/250213130927018968248.html",
            "thumbnail_pic_s": "",
            "is_content": "1"
        },
        {
            "uniquekey": "618b5e5d940c9c37d55990a4ace9cb5a",
            "title": "小柯剧场免费戏剧训练营创新“拼质”2.0 时代 开营报名火爆来袭",
            "date": "2025-02-13 13:04:00",
            "category": "娱乐",
            "author_name": "北青网",
            "url": "https://mini.eastday.com/mobile/250213130441717410813.html",
            "thumbnail_pic_s": "",
            "is_content": "1"
        }
    ]
onMounted(() => {
  console.log('娱乐新闻组件挂载')
})
onUnmounted(() => {
  console.log('娱乐新闻组件卸载')
})
</script>

<style lang="scss" scoped>
.list {
  height: 355px;
  overflow-y: auto;
}
.list ul{
  padding-left: 20px;

  li {
    padding: 10px 0;
    display: flex;
    justify-content: space-between;

    a {
      width: calc(100% - 80px);
      text-decoration: none;
      font-size: 18px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      color: #333;
    }
  }
}
</style>

App.vue 中使用组件:

<template>
  <div class="wrap">
    <div class="tab-bar">
      <span 
        v-for="item in tabBars" 
        @click="setTab(item.name)" 
        :class="{ active: current === item.name}"
      >{{ item.title }}</span>
    </div>
    <div class="tab-content">
      <component :is="tabComs[current]"></component>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import GuoNei from '@/components/GuoNei.vue'
import GuoJi from '@/components/GuoJi.vue'
import JunShi from './components/JunShi.vue';
import YuLe from './components/YuLe.vue';

const tabBars = [
  { name: 'GuoNei', title: '国内'},
  { name: 'GuoJi', title: '国际'},
  { name: 'JunShi', title: '军事'},
  { name: 'YuLe', title: '娱乐'},
]
const tabComs = {
  GuoNei,
  GuoJi,
  JunShi,
  YuLe
}

const current = ref('GuoNei')

const setTab = (tab) => {
  current.value = tab
}
</script>

<style lang="scss" scoped>
.wrap {
  width: 600px;
  height: 400px;
  border: 1px solid #ddd;
}
.tab-bar {
  display: flex;
  justify-content: space-between;

  span {
    border-left: 1px solid #ddd;
    border-bottom: 1px solid #ddd;
    padding: 10px 0;
    width: 25%;
    text-align: center;
    cursor: pointer;
    
    &:nth-child(1) {
      border-left: none;
    }

    &.active {
      background: #f04142;
      color: #fff;
    }
  }
}
</style>

这个案例中:

  • 初始化的时候,你会看到控制台打印了:国内新闻组件挂载, 说明国内新闻类型的组件发生了挂载。

image.png

  • 点击国际切换,你会看到新增了两句打印。 先打印:国内新闻组件卸载, 后打印:国际新闻组件挂载, 这说明从国内切换到国际时,Vue会先卸载国内类型的这个组件,再挂载国际这个类型的组件

  • 点击军事切换,你会看到新增了两句打印。 先打印:国际新闻组件卸载, 后打印:军事新闻组件挂载, 这说明从国际切换到军事时,Vue会先卸载国际类型的这个组件,再挂载军事这个类型的组件

  • 再切换到娱乐,相信大家已经知道结果了,这里就不做过多介绍。

  • 重新切回到国内, 你会看到新增了两句打印。 先打印:军事新闻组件卸载, 后打印:国内新闻组件挂载, 这说明从军事重新切换到国内时,Vue还是会先卸载军事类型的这个组件,再挂载国内这个类型的组件

  • 重新切回到国际, 你会看到新增了两句打印。 先打印:国内新闻组件卸载, 后打印:国际新闻组件挂载, 这说明从国内重新切换到国际时,Vue还是会先卸载国内类型的这个组件,再挂载国际这个类型的组件

结论: 在没有使用 keep-alive 的情况下,每次切换组件时,Vue 会先卸载当前组件,然后再挂载目标组件。这一过程不仅消耗了额外的带宽,尤其是在数据需要从后端请求的情况下,还可能导致用户体验不佳。

比如在我们这个例子中: 会消耗一些不必要的宽带。 这里我们使用的数据是写死的。真实情况下,这些数据一般都是从后端请求的来的。如果用户频繁切换就会频繁请求接口。会造成不必要的浪费。那么怎么解决这个问题呢? 这个时候keep-alive 就派上大用场了。

keep-alive 的初步使用:

只需要改造下App.vue 即可 在 <component :is="tabComs[current]"></component>外面包裹一个<KeepAlive>, 示例如下

    <KeepAlive>
        <component :is="tabComs[current]"></component>
      </KeepAlive>

查看运行效果:

  • 可以看到初始化的时候和之前一样的:只打印了国内新闻组件挂载
  • 切换到国际, 这个时候看到控制台就不一样了,只打印了: 国际新闻组件挂载, 没有打印: 国内新闻组件卸载,说明加了keep-alive 之后国内新闻没有卸载,只新增了国际类型组件的挂载。
  • 切换到军事,这个时候看到也只新增了一句: 军事新闻组件挂载, 没有打印国际新闻组件卸载。说明加了keep-alive 之后国际新闻没有卸载,只新增了军事类型组件的挂载。
  • 重新切换到国内,可以看到一句打印都没有新增。因为之前的国内组件没有被卸载。
  • 重新切换到国际, 同样可以看到一句打印都没有新增,因为国际组件之前也没有被卸载。

结论: 加了KeepAlive之后,只会执行初始化的挂载,之后再也不会执行挂载和卸载的过程。这样我们就解决了用户频繁操作的时候,一直请求后端接口的问题。节约了宽带,同时用户体验也提升了。用户切换的时候可以快速响应。

加了KeepAlive 之后,onMounted 不会再执行了,但是有时候我们在切换的时候还想做点事情,比如我们想统计每个类型访问的次数

onActivated

在某些情况下,我们可能希望在组件被激活时执行特定的逻辑,比如统计访问次数。此时,onActivated 钩子函数就派上了用场。与 onMounted 只在组件初次挂载时触发不同,onActivated 每次组件被激活时都会调用。

现在我们分别在国内组件,国际组件,军事组件,娱乐组件分别加上,钩子函数。

国内组件:

onActivated(() => {
  console.log('国内组件触发:onActivated')
})

国际组件:

onActivated(() => {
  console.log('国际组件触发:onActivated')
})

军事组件:

onActivated(() => {
  console.log('军事组件触发:onActivated')
})

娱乐组件:

onActivated(() => {
  console.log('娱乐组件触发:onActivated')
})

这个时候我们来看执行效果:

  • 可以看到初始化的时候新增了一句打印:国内组件触发:onActivated
  • 点击国际看到也新增了一句打印: 国际组件触发:onActivated
  • 重新切回国内:可以看到还是会打印: 国内组件触发:onActivated
  • 重新切回到国际, 也可以看到还是会打印: 国际组件触发:onActivated

结论: 由此看出,加了KeepAlive 之后,onMounted 只会执行一次,之后再也不执行,但是onActivated会一直执行。这时候我们就可以利用onActivated 解决我们想要在切换进组件时,统计每个类型的访问次数了。

在每个类型的组件新增如下代码

const count = ref(0)

在onActivated 中新增

count.value++

模板中新增:

<p>你访问了: {{ count }} 次</p>

这个时候切换就能统计出每个类型组件的访问次数了。

查看效果:

image.png

image.png

案例分析:

通过上述的实现,我们可以在实际项目中观察到明显的性能提升。以新闻类应用为例,用户在不同新闻类型之间切换时,不再感受到延迟,且数据请求次数显著减少。对于频繁切换的用户,keep-alive 的使用将大幅提升其使用体验。

总结

keep-alive 是 Vue.js 中一个强大的特性,能够有效地提升用户体验。通过避免不必要的组件卸载和挂载,它帮助开发者构建更高效的单页应用。结合 onActivated 钩子,我们可以实现更复杂的交互逻辑,如访问统计等。

在实际开发中,合理使用 keep-alive 将是提升应用性能和用户体验的重要手段。希望通过本文的介绍,能够帮助开发者更好地理解和运用这一特性,为用户提供更流畅的使用体验。