原本是想看一下大佬们的写法的,可是从csdn > 思否 > 知乎 等等,都是同一种方法,还TM都是原创,服了…
直接效果图:
代码:
<template>
<div>
<table border="solid" width="100%" cellspacing="0" cellpadding="10">
<tr>
<td>姓名</td>
<td>日期</td>
<td>年龄</td>
<td colspan="2" align="center">移动</td>
</tr>
<tr
v-for="(item,index) in testArr"
:key="item.age"
:class="{isChoose:isActive[index]}"
@click="turnSelect(index)"
ref="ref"
>
<td>{{item.date}}</td>
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td @click="up(index)" align="center">∧</td>
<td @click="down(index)" align="center">∨</td>
</tr>
</table>
<div style="position:absolute, top: 20%">
<button @click="upN">∧</button>
<button @click="downN">∨</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
testArr: [],
isActive: []
};
},
created() {
this.add();
},
methods: {
// 随机添加10个对象到数组中,下面的方法类似获取验证码,随机4个英文字母
add: function() {
for (let index = 0; index < 10; index++) {
let tit = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let t = "abcdefghijklmnopqrstuvwxyz";
let a = t.length;
let name = "";
name = tit.charAt(Math.floor(Math.random() * a));
for (let i = 0; i < 4; i++)
name += t.charAt(Math.floor(Math.random() * a));
let date = new Date().toString().slice(16, 24);
let test = { name: name, date: date, age: index + 16 };
this.testArr.push(test);
}
},
// 每个tr后面的移动
up(index) {
if (index === 0) {
return;
}
let tem = this.testArr[index - 1];
this.testArr.splice(index - 1, 1);
this.testArr.splice(index, 0, tem);
},
down(index) {
if (index === this.testArr.length - 1) {
return;
}
let tem = this.testArr[index + 1];
this.testArr.splice(index + 1, 1);
this.testArr.splice(index, 0, tem);
},
// 表格下面的移动
upN() {
this.isActive.forEach((element, index) => {
if (element === true) {
if (index === 0) {
return;
}
let tem = this.testArr[index - 1];
this.testArr.splice(index - 1, 1);
this.testArr.splice(index, 0, tem);
this.turnSelect(index - 1);
}
});
},
downN() {
let temIndex = "";
this.isActive.forEach((element, index) => {
if (element === true) {
if (index === this.testArr.length - 1) {
return;
}
let tem = this.testArr[index];
this.testArr.splice(index, 1);
this.testArr.splice(index + 1, 0, tem);
temIndex = index + 1;
}
});
this.turnSelect(temIndex || this.testArr.length - 1);
},
// 点击使得背景变色
turnSelect(index) {
this.isActive.forEach((element, index) => {
if (element === true) {
this.isActive[index] = null;
}
});
this.$set(this.isActive, index, true);
}
}
};
</script>
<style lang="scss" scoped>
.isChoose {
background-color: pink;
}
</style>
如果有不懂的留言讨论。