vue+elementui+vuex+sessionStorage实现历史标签菜单的示例代码
一般是有左侧菜单后,然后要在页面上部分添加历史标签菜单需求。
借鉴其他项目,以及网上功能加以组合调整实现
按照标签实现方式步骤来(大致思路):
1,写一个tagNav标签组件
2,在路由文件上每个路由组件都添加meta属性 meta:{title:'组件中文名'}
3,在store的mutation.js文件中写标签的添加/删除方法以及在方法中更新sessionStorage数据
4,在主页面上添加组件以及router-view外层添加keep-alive组件,我这边是main.vue为登录后主要的主页面,其他菜单页面都基于该页面的路由上
5,写一个mixins文件:beforeRouteLeave回调,因为貌似只在这回调中能找到子页面的缓存对象。在main.js中引入该文件并加入到vue.minxin()
全局方法中,节省了在每个子页面都写改回调。
6,左侧菜单也要添加路由监听,用于点标签菜单时左侧菜单能定位选中到对应的菜单选项
7,如果点标签菜单是路由重定向菜单,则需要在触发重定向的路由页面添加路由监听获取meta.title的路由属性,然后在页面的created回调中循环存放标签的store数组,并把meta.title设置为当前重定向的标签名
开始代码说明
写一个tagNav组件
@import "./base.less"; .tags-nav {display: flex; align-items: stretch; height: 40px; padding: 2px 0; background-color: @background-color; a {margin-right: 1px; width: 24px; }a:hover {color: @light-theme-color; }a:first-of-type {margin-right: 4px; }a,.dropdown-btn {display: inline-block; width:30px; height: 36px; color: @title-color; background-color: @white; text-align: center; line-height: 36px; position: relative; z-index: 10; }.tags-wrapper {flex: 1 1 auto; position: relative; .tags-wrapper-scroll {position: absolute; top: 0px; left: 0; z-index: 5; height: 36px; overflow: visible; white-space: nowrap; transition: all .3s ease-in-out; .tag {flex-shrink: 0; cursor: pointer; }}}}{{tag.title}}
以及在同层目录下的less文件
// color@theme1-color: #515a6e; @theme-color: #2d8cf0; @light-theme-color: #5cadff; @dark-theme-color: #2b85e4; @info-color: #2db7f5; @success-color: #19be6b; @warning-color: #ff9900; @error-color: #ed4014; @title-color: #17233d; @content-color: #515a6e; @sub-color: #808695; @disabled-color: #c5c8ce; @border-color: #dcdee2; @divider-color: #e8eaec; @background-color: #f8f8f9; @white: white; // 间距@padding: 16px; // 默认样式* {box-sizing: border-box; }a {color: @theme-color; }a:hover {color: @light-theme-color; }.dark-a {color: @title-color; }// 清除float.clear-float::after {display: block; clear: both; content: ""; visibility: hidden; height: 0; }// 动画.slide-fade-item {transition: all 0.1s ease-in-out; display: inline-block; }.slide-fade-enter, .slide-fade-leave-to/* .list-complete-leave-active for below version 2.1.8 */ {opacity: 0; transform: translateX(-10px); }// 滚动条样式.menu-scrollbar::-webkit-scrollbar,.common-scrollbar::-webkit-scrollbar {/*滚动条整体样式*/width: 11px; /*高宽分别对应横竖滚动条的尺寸*/height: 1px; }// 滚动条样式1.menu-scrollbar::-webkit-scrollbar-thumb {/*滚动条里面小方块*/border-radius: 2px; box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2); background: @sub-color; }// 滚动条样式2.common-scrollbar::-webkit-scrollbar-thumb {/*滚动条里面小方块*/border-radius: 2px; box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2); background: @border-color; }
-----------说明:由于这关闭所有跟关闭其他的功能只是单纯清除tagNav的标签并没关系到路由,所以获取不到清除的页面路由离开事件,只能先关闭这两功能------------
在路由文件route.js中为每个路由添加meta属性
{path: 'auditManage',name: 'auditManage',meta:{title:'审计管理'},component: function (resolve) {require(['../page/sysConfig/audit/auditManageMain.vue'], resolve); },redirect: '/main/auditManage/trendStatistics',children: [{path: 'trendStatistics',name: 'trendStatistics',meta:{title:'趋势审计'},component: function (resolve) {require(['../page/sysConfig/audit/auditTrendStatisticsList.vue'], resolve); }}, {path: 'search',name: 'search',meta:{title:'审计查询'},component: function (resolve) {require(['../page/sysConfig/audit/auditSearchList.vue'], resolve); }},
------说明:这是路由片段包含设置的meta属性方式内容,以及路由重定向-------
在store的mutation.js中写标签的添加/删除以及更新sessionStorage方法
[setPageOpenedList](state,params = null){// 设置前先读取本地保存的打开列表数据state.pageOpenedList = sessionStorage.pageOpenedList? JSON.parse(sessionStorage.pageOpenedList) : [{title: '基础设施',name: 'basicDevice',selected: true}]if (!params) {return}if (params.index === -1) {// 新打开一个页面state.pageOpenedList.push({title: params.route.meta.title,name: params.route.name,selected: false})params.index = state.pageOpenedList.length - 1}// 更新selected值for (let i = 0; i < state.pageOpenedList.length; i++) {if (params.index === i) {state.pageOpenedList[i].selected = true} else {state.pageOpenedList[i].selected = false}}// 更新下本地新的打开页面列表数据sessionStorage.pageOpenedList = JSON.stringify(state.pageOpenedList)},// 移除PageOpenedList[removePageOpenedList] (state, params = null) {if (!params) {return}if (typeof params.action === 'number') {state.pageOpenedList.splice(params.action, 1)} else {//进这里是已经选择删除所有tab,赋值一个初始选中的tabstate.pageOpenedList = [{title: '基础设施',name: 'basicDevice',selected: true}]//如果是删除其他的则再加上当前路由下的tabif (params.action === 'closeOthers' && params.route.name !== 'basicDevice') {state.pageOpenedList[0].selected = falsestate.pageOpenedList.push({title: params.route.meta.title,name: params.route.name,selected: true})}}// 更新下本地新的打开页面列表数据sessionStorage.pageOpenedList = JSON.stringify(state.pageOpenedList)},
------说明:由于有的项目中store写法不太一样,这里的
[setPageOpenedList]
以及[removePageOpenedList]
是mutation-type.js中定义的常量---------在主页面main.vue中添加标签组件、keep-alive组件、组件的选中/删除方法,监听路由的变化,计算存放的标签list
// 导航标签方法closeTags (action,elId) {let isRemoveSelected; if (typeof action === 'number') { //移除单个let elEvent = new Event('click'); document.getElementById(elId).dispatchEvent(elEvent); //移除不管是不是当前的标签都默认设置为是当前的标签for (let i = 0; i < this.$store.state.pageOpenedList.length; i++) {if (action === i) {this.$store.state.pageOpenedList[i].selected = true} else {this.$store.state.pageOpenedList[i].selected = false}}//并且是当前的标签页isRemoveSelected = this.$store.state.pageOpenedList[action].selected}this.$store.commit('removePageOpenedList', { route: this.$route, action })if (isRemoveSelected) {// 移除单个tag,导航到最后一个tag的页面this.$router.push({name: this.$store.state.pageOpenedList[this.$store.state.pageOpenedList.length - 1].name})} else if (action === 'closeAll') {this.$router.push('/main/basicDevice'); }},tagSelected (index) {if (this.$store.state.pageOpenedList[index].name !== this.$route.name) {this.$router.push({name: this.$store.state.pageOpenedList[index].name})}},
computed: {pageOpenedList () {return this.$store.getters.getPageOpenedList},},
watch: {$route (to) {// 路由变化,更新PageOpenedListlet index = this.$util.indexOfCurrentPageOpened(to.name, this.$store.state.pageOpenedList)this.$store.commit('setPageOpenedList', { route: to, index })},}
// 定位新打开的页面在pageOpenedList中位置indexOfCurrentPageOpened(name, pageOpenedList) {for (let index = 0; index < pageOpenedList.length; index++) {if (pageOpenedList[index].name === name) {return index}}return -1},
------说明:组件的导入就不贴了,缓存限制最多为5个标签,怕开太多导致浏览器内存爆炸卡死。-------
写一个minxins文件:路由离开回调,并在main.js中全局混入
/** * 用于历史标签菜单 */export default {beforeRouteLeave(to, from, next) {console.log("mixins-beforeRouteLeave:",from); let flag = truethis.$store.state.pageOpenedList.forEach(e => {// pageOpenedList存储打开的tabs的组件路由if(from.name == e.name) {flag = false}}) if(flag && this.$vnode.parent && this.$vnode.parent.componentInstance.cache) {//let key = this.$vnode.key// 当前关闭的组件名var key = (this.$vnode.key == null || this.$vnode.key == undefined) ? this.$vnode.componentOptions.Ctor.cid + (this.$vnode.componentOptions.tag ? `::${this.$vnode.componentOptions.tag}` : '') : this.$vnode.key; let cache = this.$vnode.parent.componentInstance.cache// 缓存的组件let keys = this.$vnode.parent.componentInstance.keys// 缓存的组件名if(cache[key] != null) {delete cache[key]let index = keys.indexOf(key)if(index > -1) {keys.splice(index, 1)}}}next()}}
//引入混合方法import beforeLeave from './mixins/beforeLeave'Vue.mixin(beforeLeave)
------说明:这里主要就是为在每个离开的路由页面都回调这个离开方法,并且判断当前离开的路由是切换到其他标签菜单还是关闭当前菜单标签,如果是关闭则删除对应的缓存---------
左侧菜单也要添加路由监听,以便切换标签菜单时左侧菜单能正确的跳转并选中标签
handleSelect(index,indexPath){this.active = index; },
watch:{$route (to) {console.log("accordion=============",to,to.path); //进if判断说明是被重定向的地址,则使用重定向父级菜单路径去跳转,让父级页面自己去重定向if(to.matched && to.matched[to.matched.length-1].parent.redirect != undefined){this.handleSelect(to.matched[to.matched.length-1].parent.path,null); }else {this.handleSelect(to.path,null); }}},
-----说明:第一个方法是el-menu选择菜单时触发的方法,watch路由时获取matched属性值去判断------
如果切换的标签是重定向的路由菜单则需要在重定向页面初始化时获取存放标签数组的title设置对应的radio标签(我这边项目的重定向页面基本都是用radio去切换),如果是再切换后的就是缓存的了,那就要从路由上获取title
data(){return {activeName:'参与人',menus:[{route:"partyManageReport",text:"参与人"},{route:"staffManageReport",text:"员工"},{route:"partyAccountManageReport",text:"主账号"},{route:"partyAccountGroupManageReport",text:"主账号组"},{route:"partySubAccountManageReport",text:"从账号(web资产)"},{route:"partySubAccountManageD",text:"从账号(基础设施)"}]}},watch:{$route (to){this.activeName = to.meta.title; }}, created(){this.$store.state.pageOpenedList.forEach((item)=>{if(item.selected){this.activeName = item.title; }})}
总结:由于在关闭标签方法中有添加点击事件,把关闭是其他标签时设置为当前标签并关闭,这样才能获取到关闭标签对应的路由离开回调去清除缓存。但这样就会导致关闭其他标签后当前选中的标签页会跳到最后一个标签去。如果要求不是很高,这样也能勉强接受吧。不过感觉不是那么好。有没好的方式关闭其他标签时既能清除对应的缓存当前选中的标签tab又不会跳转到其他的标签选项上…求优化思路。
另关闭所有跟关闭其他选项,还不知道怎么去清除被关闭的标签缓存,如上面所说获取不到关闭时触发路由离开方法,只是单纯重新设置标签数组而已。
文章图片
第一个是基础标签,所以把关闭按钮去了。
【vue+elementui+vuex+sessionStorage实现历史标签菜单的示例代码】到此这篇关于vue+elementui+vuex+sessionStorage实现历史标签菜单的示例代码的文章就介绍到这了,更多相关vue 历史标签菜单内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!