概述
在现代 web 应用中,tab 页签功能是非常常见的一种交互模式。它可以帮助用户在不同的视图间快速切换,而不会丢失当前视图的状态。为了进一步提升用户体验,我们可以通过 keep-alive 组件来缓存已经打开的视图,这样即使用户离开并再次回到这个视图,也可以看到之前的状态。
本文将介绍如何在 vue 项目中实现一个带有缓存功能的 tab 页签功能。
效果实现
点击左侧菜单栏,添加tab页及页面缓存,关闭tab页,删除页面缓存
功能实现(只展示核心代码)
一、使用 keep-alive 缓存路由
为了实现页面缓存,我们需要使用 keep-alive 组件。首先,在 app.vue 中引入 keep-alive 并
将其包裹在 <router-view> 外面。同时,我们可以使用 include 属性来指定哪些组件应该被缓存。
<!-- 缓存路由 --> <keep-alive :include="cacheviews"> <router-view></router-view> </keep-alive>
二、点击左侧菜单,添加页签并添加缓存标记
在左侧菜单栏组件(例如 menutree.vue)中,我们需要监听用户的点击事件,以便在点击某个菜单项时添加新的页签。同时,我们也需要将该组件的 name 添加到 cachedviews 数组中,以标记该组件应被缓存。请注意,这里的 name必须与页面组件name、路由name保持一致。
// 点击左侧菜单时添加tab页签,添加缓存页面 const findindex = this.existedtabs.findindex(v => { return v.name == item.name }) if(findindex == -1) { // tab页签中不存在,push进去 this.existedtabs.push(item); this.cacheviews.push(item.name) } this.$store.commit("savetabslist", this.existedtabs); // 保存tab标签页 this.$store.commit("savecacheviews", this.cacheviews); // 保存需要缓存页面组件
三、关闭页签,删除缓存标记
在关闭页签时,我们需要从 cachedviews
数组中移除对应的组件名称,以取消对该组件的缓存。
// 关闭tab页签时,删除缓存标记 const findindex = this.tabslistarray.findindex((v) => { return v.name == targetname; }); if (findindex > -1) { this.tabslistarray.splice(findindex, 1); const findindexcacheviews = this.cacheviews.indexof(targetname); if (findindexcacheviews > -1) { this.cacheviews.splice(findindex, 1); } } this.$store.commit("savetabslist", this.tabslistarray); this.$store.commit("savecacheviews", this.cacheviews); if (targetname == this.activename) { // 当前菜单,跳转至后面/前面一个菜单 if (findindex < this.tabslistarray.length) { this.$router.push({ name: this.tabslistarray[findindex].name, }); } else { this.$router.push({ name: this.tabslistarray[findindex - 1].name, }); } }
总结来说,通过上述步骤,我们成功实现了动态添加菜单页签并缓存功能。在实际应用中,还需要考虑一些细节,如处理未缓存页面的刷新等。希望这篇文章能对您有所帮助!
到此这篇关于vue实现一个带有缓存的tab页签功能的文章就介绍到这了,更多相关vue实现tab页签内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论