keep-alive缓存文章列表案例完整代码(Vue3)

keep-alive缓存文章列表案例完整代码(Vue3)

环境准备

创建一个项目

bash 复制代码
vue create 项目名

也可以用 vite

bash 复制代码
npm create vite@latest 项目名 --template vue

安装 vue router

bash 复制代码
npm install vue-router@4

目录结构

完整代码

main.js

js 复制代码
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";

createApp(App).use(router).mount("#app");

App.vue

这里和vue2一样也有两种写法,可以看 keep-alive缓存文章列表案例完整代码(Vue2)

这边就用第二种。

js 复制代码
<template>
  <RouterView v-slot="{ Component }">
    <KeepAlive>
      <component :is="Component" v-if="route.meta.keepAlive" />
    </KeepAlive>
    <component :is="Component" v-if="!route.meta.keepAlive" />
  </RouterView>
</template>
<script setup>
import { useRoute } from "vue-router";
const route = useRoute();
</script>

ArticleList.vue

js 复制代码
<script setup>
import {
  onMounted,
  onActivated,
  onDeactivated,
  ref,
  nextTick,
  onUnmounted,
} from "vue";

const articles = ref([]);
const scrollTop = ref(0);

function fakeFetch() {
  return Array.from({ length: 100 }, (_, i) => ({
    id: i + 1,
    title: "文章标题 " + (i + 1),
  }));
}

function handleScroll() {
  scrollTop.value = window.scrollY || document.documentElement.scrollTop;
  // console.log("滚动位置:", scrollTop.value);
}

onMounted(() => {
  // console.log("mounted:" + scrollTop.value);
  articles.value = fakeFetch();
  window.addEventListener("scroll", handleScroll);
});

//onUnmounted(() => {
//  console.log("unmounted"); // 有就说明没缓存成功
//});

onActivated(() => {
	nextTick(() => {
		// console.log("activated:", scrollTop.value);
		window.scrollTo(0, scrollTop.value);
	  });
	window.addEventListener("scroll", handleScroll);
});

onDeactivated(() => {
  // console.log("deactivated:", scrollTop.value);
  window.removeEventListener("scroll", handleScroll);
});
</script>

<template>
  <div>
    <div v-for="item in articles" :key="item.id" class="item">
      <router-link :to="{ name: 'ArticleDetail', query: { id: item.id } }">
        {{ item.title }}
      </router-link>
    </div>
  </div>
</template>

<style>
.item {
  padding: 16px;
  border-bottom: 1px solid #eee;
}
</style>

ArticleDetail.vue

js 复制代码
<script setup>
import { onMounted } from "vue";
import { useRoute } from "vue-router";

// 获取路由信息
const route = useRoute();

onMounted(() => {
  // 模拟请求内容
  // console.log("详情页 mounted,ID:", route.query.id);
});
</script>

<template>
  <div>
    <h2>文章详情 {{ route.query.id }}</h2>
    <p>内容详情...</p>
    <router-link to="/list">返回列表</router-link>
  </div>
</template>

router.js

js 复制代码
import { createRouter, createWebHistory } from "vue-router";
import ArticleList from "@/components/ArticleList.vue";
import ArticleDetail from "@/components/ArticleDetail.vue";

const routes = [
  {
    path: "/list",
    name: "ArticleList",
    component: ArticleList,
    meta: { keepAlive: true },
  },
  {
    path: "/detail",
    name: "ArticleDetail",
    component: ArticleDetail,
    meta: { keepAlive: false },
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

export default router;

vue2 版本

keep-alive缓存文章列表案例完整代码(Vue2)

相关推荐
asdfg12589639 分钟前
JS中的闭包应用
开发语言·前端·javascript
kirk_wang11 分钟前
Flutter 导航锁踩坑实录:从断言失败到类型转换异常
前端·javascript·flutter
梦里不知身是客1131 分钟前
spark中如何调节Executor的堆外内存
大数据·javascript·spark
静小谢1 小时前
前后台一起部署,vite配置笔记base\build
前端·javascript·笔记
用户47949283569151 小时前
改了CSS刷新没反应-你可能不懂HTTP缓存
前端·javascript·面试
OpenTiny社区2 小时前
2025OpenTiny星光ShowTime!年度贡献者征集启动!
前端·vue.js·低代码
wangan0942 小时前
不带圆圈的二叉树
java·前端·javascript
狗哥哥2 小时前
从零到一:打造企业级 Vue 3 高性能表格组件的设计哲学与实践
前端·vue.js·架构
计算机毕设VX:Fegn08952 小时前
计算机毕业设计|基于springboot + vue图书借阅管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
JohnYan2 小时前
Bun技术评估 - 22 Stream
javascript·后端·bun