概述
在现代 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,
});
}
}
总结来说,通过上述步骤,我们成功实现了动态添加菜单页签并缓存功能。在实际应用中,还需要考虑一些细节,如处理未缓存页面的刷新等。希望这篇文章能对您有所帮助!