在 Vue.js 中,结合 Element UI 和 sortablejs
,我们可以轻松实现表格的行拖拽功能。本文将演示如何在 Vue 项目中使用这些工具,并在拖拽后将数据更新到后端服务系统。
1、安装sortablejs
npm install element-ui sortablejs
2、在用到的页面引入文件
import Sortable from 'sortablejs'
3、示例代码
以下是一个包含表格行拖拽功能的 Vue 组件示例:
row-key="id"
用于指定每行数据的唯一键值,这里假设每个数据项都有一个唯一的id
字段。- mounted() 钩子在组件被挂载到 DOM 后执行。这里使用 this.$nextTick 确保所有的子组件也被渲染。
在 mounted 内部,我们通过 this.$el.querySelector 获取表格的 DOM 元素,并使用 Sortable.create 初始化拖拽功能。
<template>
<div class="table">
<el-table :data="questionList" row-key="id">
<el-table-column type="index" label="序号">
</el-table-column>
<el-table-column prop="name" label="考题">
</el-table-column>
<el-table-column prop="type" label="类别">
</el-table-column>
<el-table-column prop="score" label="分值">
</el-table-column>
</el-table>
</div>
</template>
<script>
import Sortable from 'sortablejs'
export default {
data() {
return {
questionList: [{
id: 1,
name: '单选题123',
type: '单选题',
score: 10
}, {
id: 2,
name: '多选题456',
type: '多选题',
score: 20
}, {
id: 3,
name: '简答题789',
type: '简答题',
score: 10
}],
};
},
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.questionList.splice(oldIndex, 1)[0]
this.questionList.splice(newIndex, 0, movedItem)
},
},
};
</script>