一、前言
在现代前端开发中,Vue.js 作为一款流行的 JavaScript 框架,广泛应用于构建交互性强、用户体验优良的应用程序。在许多应用场景中,标签(tag)栏提供了一种便捷的方式来组织和展示信息。用户可以通过标签来快速识别内容,增强界面的可用性。然而,随着用户需求的变化,标签的管理变得越来越重要,特别是在需要动态添加和移除标签的情况下。实现可移除标签的功能,不仅能提高用户的操作灵活性,还能提升应用的整体体验。本文将介绍如何在 Vue 2 中实现可移除标签栏的功能,通过简单的示例和步骤,帮助开发者快速上手。我们将从基础的标签组件开始,逐步扩展到实现标签的添加和移除功能,最终实现一个可交互的标签栏。
二、在Store/tab.js中实现closeTag关闭标签栏的函数
mutations: {
...其他方法
//关闭标签页,删除指定的tag数据
closeTag(state, item) {
// console.log(item)
const index = state.tabsList.findIndex(val => val.name === item.name)
//位置加个数
state.tabsList.splice(index, 1)
}
}
三、CommonTag.vue组件
<template>
<div class="tags">
<el-tag v-for="(item, index) in tags" :key="item.path" :closable="item.name !== 'home'"
:effect="$route.name === item.name ? 'dark' : 'light'" @click="changeMenu(item)"
@close="handleClose(item, index)" size="small">
{
{ item.label }}
</el-tag>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
export default {
name: 'CommonTag',
data() {
return {}
},
computed: {
...mapState({
tags: state => state.tab.tabsList
})
},
methods: {
//调用函数
...mapMutations(['closeTag']),
changeMenu(item) {
// this.$store.commit('closeTab', item) 通过对象的方式进行跳转
this.$router.push({ name: item.name })
},
//点击删除的逻辑
handleClose(item, index) {
//调用store中的mutation方法
this.closeTag(item)
const length = this.tags.length
console.log(9023901);
console.log(length);
//删除之后的跳转逻辑
if (item.name !== this.$route.name) {
return
}
if (index === length) {
this.$router.push({
name: this.tags[index - 1].name
})
} else {
this.$router.push({
name: this.tags[index].name
})
}
}
}
}
</script>
<style lang="less" scoped>
.tags {
padding: 20px;
.el-tag {
margin-right: 15px;
cursor: pointer;
}
}
</style>
四、在MainPage中挂载组件 CommonTag.vue
<common-tag />
<script
import CommonTag from '@/components/CommonTag.vue'
export default {
name: 'MainPage',
data() {
return {
}
},
components: {
CommonTag
}
}
</script>