本来我想实现这样的tab切换效果,能删除和添加
但看了看elementui的文档,有点不太一样
添加按钮跑天上去了,所以我就基于原本功能做了一些优化以实现我想要的结果
1.首先在循环的el-tab-pane下面单独添加一个el-tab-pane,并取一个特别的名字,我叫add
<el-tabs v-model="editableTabsValue" type="card"
@tab-remove="removeTab"
:before-leave="beforeLeave"
class="my-tab-pane"
>
<el-tab-pane
v-for="(item, index) in editableTabs"
:key="item.name"
:label="item.title"
:name="item.name"
closable
>
</el-tab-pane>
<el-tab-pane key="add" name="add" >
<span slot="label" style="padding: 8px;font-size:20px;font-weight:bold;">
+
</span>
</el-tab-pane>
</el-tabs>
2.data
data() {
return {
editableTabsValue: '1',
currentIndex:1,
editableTabs: [{
title: '活动1',
name: '1',
}],
tabIndex: 1,
addIndex:1,
}
},
3.添加删除方法
addTab() {
let newTabIndex = ++this.tabIndex + '';
this.editableTabs.push({
title: '活动'+ ++this.addIndex,
name: newTabIndex,
});
this.editableTabsValue = newTabIndex;
this.currentIndex=newTabIndex;
},
removeTab(targetName) {
if(this.editableTabs.length<=1){
return false;
}
var self=this;
let tabs = self.editableTabs;
let activeName = self.editableTabsValue;
if (activeName === targetName) {
tabs.forEach((tab, index) => {
if (tab.name === targetName) {
let nextTab = tabs[index + 1] || tabs[index - 1];
if (nextTab) {
activeName = nextTab.name;
}
}
});
}
self.editableTabsValue = activeName;
self.editableTabs = tabs.filter(tab => tab.name !== targetName);
self.editableTabs.map((tab,index)=>{
tab.title="活动"+(index+1);
self.addIndex=(index+1);
})
self.currentIndex=self.editableTabsValue;
self.$message({
type: 'success',
message: '删除成功!'
});
},
/* 活动标签切换时触发 */
beforeLeave(currentName,oldName) {
var self=this;
//重点,如果name是add,则什么都不触发
if(currentName=="add"){
this.addTab()
return false
}else{
this.currentIndex=currentName;
}
}
总结:
其实添加这个按钮本质和tab一样,但是点它不切换标签,而是调用添加方法。