vue 表格数据上下移动并增加背景色

在Vue中实现表格数据上下移动并添加背景色,可以通过操作数组来重新排序表格行,并使用计算属性或方法来为特定条件设置背景色。以下是一个简单的示例:

<template>
  <div>
    <table>
      <thead>
        <tr>
          <th>序号</th>
          <th>名称</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in items" :key="item.id" :style="{ background: getRowBackground(index) }">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>
            <button @click="moveUp(index)" :disabled="index === 0">上移</button>
            <button @click="moveDown(index)" :disabled="index === items.length - 1">下移</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      items: [
        { id: 1, name: 'Item 1' },
        { id: 2, name: 'Item 2' },
        { id: 3, name: 'Item 3' },
        // ...
      ]
    };
  },
  methods: {
    moveUp(index) {
      if (index > 0) {
        const temp = this.items[index];
        this.$set(this.items, index, this.items[index - 1]);
        this.$set(this.items, index - 1, temp);
      }
    },
    moveDown(index) {
      if (index < this.items.length - 1) {
        const temp = this.items[index];
        this.$set(this.items, index, this.items[index + 1]);
        this.$set(this.items, index + 1, temp);
      }
    }
  },
  computed: {
    getRowBackground() {
      // 根据需要设置特定行的背景色,例如:选中行或其他条件
      return (index) => {
        // 假设我们将第一行和最后一行设置为特殊颜色
        if (index === 0 || index === this.items.length - 1) {
          return '#ffcc00'; // 黄色背景
        }
        return ''; // 默认背景色
      };
    }
  }
};
</script>

moveUp 和 moveDown 方法用于将选定的表格行上移或下移一行。getRowBackground 计算属性用于根据行的索引设置行的背景色。

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晨曦_子画

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值