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)

相关推荐
摇一摇小肉包的JAVA笔记2 小时前
Redis如何解决缓存击穿,缓存雪崩,缓存穿透
数据库·redis·缓存
黑客飓风2 小时前
JavaScript性能优化实战
开发语言·javascript·性能优化
江城开朗的豌豆5 小时前
Vue组件CSS防污染指南:让你的样式乖乖“宅”在自家地盘!
前端·javascript·vue.js
江城开朗的豌豆5 小时前
Vue组件花式传值:祖孙组件如何愉快地聊天?
前端·javascript·vue.js
浩男孩6 小时前
【🍀新鲜出炉 】十个 “如何”从零搭建 Nuxt3 项目
前端·vue.js·nuxt.js
拉不动的猪7 小时前
pc和移动页面切换的两种基本方案对比
前端·javascript·vue.js
Hilaku7 小时前
前端日志调试也能专业化?我们这样设计日志系统
前端·javascript
花果山总钻风7 小时前
Debian 编译安装 ruby3.2
前端·javascript·debian
BUG收容所所长7 小时前
深入理解 AJAX,从 XMLHttpRequest 到现代 Fetch API
前端·javascript·ajax
Sun_light7 小时前
「一文看懂 JS 深浅拷贝,彻底告别面试踩坑!」
前端·javascript