Vue+ElementUI skill sharing: Combining Sortablejs to implement table row drag and drop


Preface

In many dynamic web applications, the interactivity of the user interface is the key to improving the user experience. In Vue.js, combined with Element UI and sortablejs, we can easily implement the row dragging function of the table. This article will demonstrate how to use these tools in a Vue project and update data to the backend service system after dragging and dropping.


Preparation

Make sure you have Element UI and sortablejs installed in your project. If it is not installed yet, you can install it with the following command:

npm install element-ui sortablejs

Introduce Element UI and its styles in your main entry file (such as main.js or app.js):

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

Vue.use(ElementUI);

Sample code

The following is an example of a Vue component that includes table row dragging functionality:

<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>

This code demonstrates how to combine the Element UI table and sortablejs in the Vue component to implement the row dragging function. The main steps include initializing the table data, configuring sortablejs to enable drag and drop, and updating the data and synchronizing to the server when the drag is completed. This way you can create an interactive and user-friendly table interface.

Code description

1. Introduce dependencies and component structure

<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>The section defines the HTML structure of the component. The <el-table> component of Element UI is used here to create the table.
  • :data="planTableData" is a dynamic property (Vue's shorthand for v-bind) that binds the planTableData array to the table's data source.
  • row-key="id" is used to specify a unique key value for each row of data. It is assumed that each data item has a unique id field.
  • import Sortable from 'sortablejs' introduces the sortablejs library, which is used to implement drag and drop functionality.
  • import axios from 'axios' introduces the axios library for sending HTTP requests.

2. Component data and life cycle

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()The function returns the responsive data of the component, here is the planTableData array, used to store table data.
  • created() life cycle hook is used to initialize planTableData. This can be replaced by loading data from the server.
  • mounted() hook is executed after the component is mounted to the DOM. Using this.$nextTick here ensures that all child components are also rendered.
  • Inside mounted, we get the DOM element of the table through this.$el.querySelector and use Sortable.create to initialize the drag and drop function.

3. Implement drag and drop function

Sortable.create(el, {
    
    
  onEnd: (event) => {
    
    
    const {
    
     oldIndex, newIndex } = event
    this.updateRowOrder(oldIndex, newIndex)
  }
})
  • Sortable.createAccepts two parameters: the element to which dragging is to be applied and the configuration object.
  • onEndIs an event handler, triggered when the drag operation is completed.
  • eventThe parameter provides details of the drag operation, including the original index oldIndex and the new index newIndex.
  • this.updateRowOrderIs a custom method used to update the order of elements in an array.

4. Update data and server synchronization

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 adjusts the position of the element in through the splice method of the array. planTableData
  • updateOrderOnServer Use axios to send a POST request to the server to synchronize the updated sequence. ‘/api/update-order’ here is a sample API endpoint and needs to be adjusted according to the actual backend service.

running result

Operation effect 1
Running effect 2


Summarize

By combining Vue.js, Element UI and sortablejs, we can effectively implement a user-friendly drag-and-drop table interface and ensure data consistency through the backend Interactive maintenance of services. This not only improves the interactivity of the application but also enhances the user experience.

Guess you like

Origin blog.csdn.net/qq_31463571/article/details/134843125