前言

在很多动态网页应用中,用户界面的交互性是提高用户体验的关键。在 Vue.js 中,结合 Element UI 和 sortablejs,我们可以轻松实现表格的行拖拽功能。本文将演示如何在 Vue 项目中使用这些工具,并在拖拽后将数据更新到后端服务系统。


准备工作

确保你的项目中已经安装了 Element UI 和 sortablejs。如果还没有安装,可以通过以下命令进行安装:

npm install element-ui sortablejs

在你的主入口文件(如 main.jsapp.js)中引入 Element UI 和其样式:

import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

Vue.use(ElementUI);

示例代码

以下是一个包含表格行拖拽功能的 Vue 组件示例:

<template>
  <div>
    <el-table :data="planTableData"
              row-key="id">
      <el-table-column prop="createTime"
                       label="日期"
                       width="180"></el-table-column>
      <el-table-column prop="event"
                       label="事件"
                       width="180"></el-table-column>
      <!-- 其他列 -->
    </el-table>
  </div>
</template>

<script>
import Sortable from 'sortablejs'
import axios from 'axios' // 引入axios进行HTTP请求

export default {
  name: 'PlanTableDraggable',
  data () {
    return {
      planTableData: []
    }
  },
  created () {
    this.planTableData = [
      { id: 1, createTime: '2023-01-01', event: '事件1' },
      { id: 2, createTime: '2023-01-02', event: '事件2' },
      { id: 3, createTime: '2023-01-03', event: '事件3' }
      // ...更多测试数据
    ]
  },
  mounted () {
    this.$nextTick(() => {
      const el = this.$el.querySelector('.el-table__body-wrapper tbody')
      Sortable.create(el, {
        onEnd: (event) => {
          const { oldIndex, newIndex } = event
          this.updateRowOrder(oldIndex, newIndex)
        }
      })
    })
  },
  methods: {
    updateRowOrder (oldIndex, newIndex) {
      const movedItem = this.planTableData.splice(oldIndex, 1)[0]
      this.planTableData.splice(newIndex, 0, movedItem)
      this.updateOrderOnServer()
    },
    updateOrderOnServer () {
      axios.post('/api/update-order', { newOrder: this.planTableData })
        .then(response => {
          console.log('Order updated:', response)
        })
        .catch(error => {
          console.error('Error updating order:', error)
          // 可能需要回滚操作
        })
    }
  }
}
</script>

这段代码演示了如何在 Vue 组件中结合 Element UI 的表格和 sortablejs 来实现行拖拽功能。主要步骤包括初始化表格数据、配置 sortablejs 来启用拖拽,并在拖拽结束时更新数据和同步到服务器。通过这种方式,您可以创建一个交互式且用户友好的表格界面。

代码说明

1. 引入依赖和组件结构

<template>
  <div>
    <el-table :data="planTableData" row-key="id">
      <!-- 表格列 -->
    </el-table>
  </div>
</template>

<script>
import Sortable from 'sortablejs'
import axios from 'axios'

export default {
  // ...
}
</script>
  • <template> 部分定义了组件的 HTML 结构。这里使用了 Element UI 的 <el-table> 组件来创建表格。
  • :data="planTableData" 是一个动态属性(Vue 的 v-bind 简写),它绑定 planTableData 数组到表格的数据源。
  • row-key="id" 用于指定每行数据的唯一键值,这里假设每个数据项都有一个唯一的 id 字段。
  • import Sortable from 'sortablejs' 引入 sortablejs 库,它用于实现拖拽功能。
  • import axios from 'axios' 引入 axios 库,用于发送 HTTP 请求。

2. 组件数据和生命周期

export default {
  name: 'PlanTableDraggable',
  data () {
    return {
      planTableData: []
    }
  },
  created () {
    this.planTableData = [/* 初始数据 */]
  },
  mounted () {
    this.$nextTick(() => {
      const el = this.$el.querySelector('.el-table__body-wrapper tbody')
      Sortable.create(el, {/* 配置项 */})
    })
  },
  // ...
}
  • data() 函数返回组件的响应式数据,这里是 planTableData 数组,用于存储表格数据。
  • created() 生命周期钩子用于初始化 planTableData。这里可以替换为从服务器加载数据。
  • mounted() 钩子在组件被挂载到 DOM 后执行。这里使用 this.$nextTick 确保所有的子组件也被渲染。
  • mounted 内部,我们通过 this.$el.querySelector 获取表格的 DOM 元素,并使用 Sortable.create 初始化拖拽功能。

3. 实现拖拽功能

Sortable.create(el, {
  onEnd: (event) => {
    const { oldIndex, newIndex } = event
    this.updateRowOrder(oldIndex, newIndex)
  }
})
  • Sortable.create 接受两个参数:要应用拖拽的元素和配置对象。
  • onEnd 是一个事件处理器,当拖拽操作完成时触发。
  • event 参数提供了拖拽操作的详情,包括原始索引 oldIndex 和新索引 newIndex
  • this.updateRowOrder 是一个自定义方法,用于更新数组中元素的顺序。

4. 更新数据和服务器同步

methods: {
  updateRowOrder (oldIndex, newIndex) {
    const movedItem = this.planTableData.splice(oldIndex, 1)[0]
    this.planTableData.splice(newIndex, 0, movedItem)
    this.updateOrderOnServer()
  },
  updateOrderOnServer () {
    axios.post('/api/update-order', { newOrder: this.planTableData })
      .then(response => {
        console.log('Order updated:', response)
      })
      .catch(error => {
        console.error('Error updating order:', error)
      })
  }
}
  • updateRowOrder 通过数组的 splice 方法调整 planTableData 中元素的位置。
  • updateOrderOnServer 使用 axios 发送一个 POST 请求到服务器,以同步更新后的顺序。这里的 ‘/api/update-order’ 是示例 API 端点,需要根据实际后端服务进行调整。

运行效果

Vue+ElementUI技巧分享:结合Sortablejs实现表格行拖拽-LMLPHP
Vue+ElementUI技巧分享:结合Sortablejs实现表格行拖拽-LMLPHP


总结

通过结合 Vue.js、Element UI 和 sortablejs,我们可以有效地实现一个交云用户友好的拖拽表格界面,并确保数据的一致性通过与后端服务的交互维护。这不仅提高了应用程序的交互性,还增强了用户体验。

12-07 11:46