在后台系统中,常用一中页面标签工具,每次点击菜单栏时,会在顶部增加一个标签,可关闭,可切换页面等功能,常见于后台管理中。
原理:
1、点击菜单栏时,将菜单项的数据记录在vuex中,或者本地的storage中,哪种都可以,主要时保存数据。
2、上方标签,通过读取路由链,然后渲染出顶部的标签(vue中的tag)
3、关闭,点击关闭后,要i删除路由链,并且要跳转,当然这里要判断,如果关闭当前页,则往后面跳转。
代码落地:
1、store文件下 添加tags.js
import router from '@/router'
const tags = {
namespaced: true,
state: {
tagsList:[]
},
mutations: {
// //设置当前的tag页为活动页
setTagsList (state, curTag) {
for (let i = 0; i < state.tagsList.length;i++) {
state.tagsList[i].isActive = false
if (state.tagsList[i].name === curTag.name) {
state.tagsList[i].isActive = true
}
}
console.log('tagsList的值',state.tagsList);
},
//选择菜单后,如果不存在就--添加至本地路由信息中
addRoute (state, curTag) {
console.log('执行了添加',curTag);
let target = state.tagsList.find(item => item.name === curTag.name)
let targetIndex = state.tagsList.findIndex(item => item.name === curTag.name)
if (!target) {
state.tagsList.push({
path: curTag.path,
name: curTag.name,
meta: curTag.meta,
})
} else {
state.tagsList.splice(targetIndex, 1,target)
}
this.commit('tags/setTagsList', curTag)
},
delRoute (state, curTag) {
let targetIndex = state.tagsList.findIndex(item => item.name === curTag.name)
state.tagsList.splice(targetIndex, 1)
let last = state.tagsList[state.tagsList.length - 1]
console.log(this);
router.push({ path:last.path })
this.commit('tags/setTagsList',last)
},
},
}
export default tags
2、设置一下路由信息 router/index.js 在路由前置守卫中每次点击进行添加到store中
router.beforeEach(async (to, from, next) => {
try {
const loginName = await getUserInfo()
const id = loginName.id
setDeskUrl(id, to?.path)
store.commit('tags/addRoute', to)
next()
} catch (error) {
}
3、tags组件
<template>
<div class="menu-tags">
<a-tag
:class="['menu-tags_item', item.isActive ? 'item_active' : '']"
closable
v-for="(item, index) in tagData"
:key="item.name + index"
@close="handleClose(item)"
@click="handleSelect(item)"
>
<span :class="item.isActive ? 'item_active' : ''">{{
item.meta.title
}}</span>
</a-tag>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
export default {
name: 'Tags',
props: {},
data() {
return {
data: [],
}
},
computed: {
...mapState({
tagData() {
console.log(222,this.$store.state.tags.tagsList);
return this.$store.state.tags.tagsList
},
}),
},
// 页面方法
methods: {
...mapMutations('tags',{
mySetRouterTagActive: 'setTagsList',
}),
handleClose(item) {
this.$store.commit('tags/delRoute',item)
},
handleSelect(item) {
//如果是当前页,则不跳
if (item.name != this.$route.name) {
this.$router.push({
path: item.path,
})
// this.$store.commit('tags/addRoute',item)
}
},
},
}
</script>
<style lang="less" scoped>
.menu-tags {
margin-left: 16px;
.menu-tags_item {
padding: 2px 10px;
cursor: pointer;
}
.menu-tags_item:hover {
color: #63d5ce;
}
.item_active {
color: #63d5ce;
}
}
</style>
4、引到页面中,放在layout布局 或者App.vue中,大家可以根据自己的要求放在指定位置即可