业务需求说明: 例如:tabs1、tabs2、tabs3、tabs4 tabs2改为tabs4(往后移)则顺序变为tabs1、tabs3、tabs4、tabs2; tabs4改为tabs2(往前移) 则顺序变为tabs1、tabs4、tabs2、tabs3。
父页面:tabs.vue
<template>
<div>
<p>
<el-button type="primary" size="small" @click="addTab(tabs.length)">添加</el-button>
</p>
<el-tabs v-model="activeTab" type="card" closable @tab-remove="removeTab">
<el-tab-pane ref="tabs" v-for="(item, index) in tabs" :key="index" :label="'Tab' + tabs[index].sort"
:name="index + ''">
<InputSort :tabs="item" @changeSort="changeSort" :maxInput="tabs.length">
</InputSort>
</el-tab-pane>
</el-tabs>
</div>
</template>
<script>
import InputSort from "../components/InputSort";
export default {
name: "tabs",
components: {
InputSort
},
data() {
return {
activeTab: '0',
tabs: [{
sort: 1,
content: ''
}]
};
},
methods: {
changeSort(e) {
this.$nextTick(() => {
let currentIndex = this.activeTab * 1
let changeIndex = e.sort - 1
let tabs = this.tabs;
let [a] = tabs.splice(currentIndex, 1)
tabs.splice(changeIndex, 0, a)
this.activeTab = changeIndex + ''
tabs.map((item, index) => {
item.sort = index + 1
})
if (e.sort == undefined) {
tabs[currentIndex].sort = currentIndex + 1
return
}
})
},
addTab(val) {
console.log(val)
if (this.tabs.length >= 10) {
alert("最多支持10个Tab")
} else {
this.tabs.push({
sort: val + 1,
content: ''
})
}
this.activeTab = (this.tabs.length - 1) + ''
},
removeTab(targetName) {
if (confirm("确认要删除吗?")) {
if (this.tabs.length > 1) {
let tabs = this.tabs;
let activeName = this.activeTab;
if (activeName >= targetName) {
activeName = (activeName - 1) + ''
}
tabs.splice(targetName * 1, 1)
this.activeTab = activeName;
tabs.map((item, index) => {
if (index >= (targetName * 1)) {
item.sort = item.sort - 1
}
})
this.tabs = tabs
} else {
alert("请至少保留一个Tab")
}
}
},
}
};
</script>
如果是替换顺序,则
changeSort(e) {
this.$nextTick(() => {
[this.tabs[e.sort - 1], this.tabs[this.activeTab * 1]] = [this.tabs[this.activeTab * 1], this.tabs[e.sort - 1]]
this.tabs[this.activeTab * 1].sort = this.activeTab * 1 + 1;
this.activeTab = e.sort - 1 + ''
})
}
子页面:InputSort.vue
<template>
<div>
<el-form ref="form" :model="form" :rules="rules" size="medium" label-width="100px">
<el-form-item label="序号:" prop="sortNum">
<el-input-number size="small" v-model="tabs.sort" :min="1" :max="maxInput" @change="changeSort">
</el-input-number>
</el-form-item>
<el-form-item label="内容:" prop="content">
<el-input type="text" placeholder="请输入" v-model="tabs.content" maxlength="5" show-word-limit
style="width:160px">
</el-input>
</el-form-item>
</el-form>
</div>
</template>
<script>
export default {
name: "InputSort",
props: {
maxInput: Number,
tabs: Object,
},
data() {
return {
form: this.tabs,
rules: {
content: [
{ required: true, message: '请输入内容', trigger: 'blur' },
],
}
}
},
methods: {
changeSort() {
this.$emit('changeSort', this.form)
},
}
};
</script>
源码下载:https://download.csdn.net/download/weixin_45421804/85813374
|