一、实现效果
最近遇到一个需求想要同一个菜单能多次打开,生成多个Tag标签,废话不多说,上图
form菜单,我打开了3个窗口, 窗口的内容是独立的,我是通过动态路由的方式实现的,感觉效果不是很理想,代码如下
二、项目目录结构
三、核心代码
// vuex不做判断,直接插入集合
state: {
...
barList: []
},
SET_BAR_LIST: (state, content) => {
// let ind = state.barList.findIndex(el => el.key === content.key)
// if(ind == -1) {
// state.barList.push(content)
// }
state.barList.push(content)
},
// xTabbar页面取到vuex的数据
computed: {
menus() {
return this.$store.getters.barList
}
},
// sideMenu页面 菜单点击时生成Tag集合
handleSelect(keyPath, key) {
let num = Math.random()
this.$router.push({name: key, params: {id: num}})
this.$store.dispatch('setBarList', { keyPath, key, num})
}
// 路由配置
{
path: '/example',
component: Layout,
redirect: '/example/home',
name: 'Example',
meta: {
title: 'Example',
icon: 'example'
},
children: [{
// path: 'form',
path: 'form/:id', // 用于多tag
name: 'Form',
component: () => import('@/page/form.vue'),
meta: {
title: 'Form',
}
},
{
// path: 'about',
path: 'about/:id', // 用于多tag
name: 'About',
component: () => import('@/page/about.vue'),
meta: {
title: 'About',
}
}
]
},
———————————————————————————我是分割线——————————————————————————
四、升级改造
以前是用随机数,太low,今天进行优雅的升级
首先将路由进行改造,去除'form/:id'中的‘/’
{
path: 'form:id', // 用于多tag
name: 'Form',
component: () => import('@/page/form.vue'),
meta: {
title: 'Form',
}
}
然后菜单页面进行改造,num不再使用随机数
// 点击菜单,生成Tag标签集合
handleSelect(keyPath, key) {
let num = this.barList.filter(e => e.key == key).length
this.$router.push({name: key, params: {id: num}})
// 将地址,名称,随机数存入vuex,标签点击时可以跳转回去
this.$store.dispatch('addBarList', { keyPath: keyPath.replace(':id', num), key, num})
},
最后实现的效果,form地址后面递增加1 ,
——————————————————————————我是分割线———————————————————————————
五、额外效果
额外效果展示,右键关闭,tag左右滑动,实现效果如有需要,请评论区留言
六、仓库地址