需求描述:
在element-ui 的 el-table中实现数据行与行之间丝滑的拖拽功能。
使用插件:
因为做一个拖拽的功能,所以多番考察后采用了sortable.js。
- 参考中文网址:sortable.js中文文档 - itxst.com
- npm安装方式:npm install sortablejs --save
- 安装后导入:import Sortable from 'sortablejs';
一些拖拽事件和要求网址里都有写到,但像小编这个段位的前端,表示e.........
代码:
首先这是根据项目需求写的,所以数据就直接用后端返回的写到tableData中了。
html中:
<el-table v-loading="loadingFlag" :data="tableData" row-key="id" border>
<el-table-column type="index" label="序号" align="center" width="60" />
<el-table-column prop="name" label="字段名称" align="center" />
<el-table-column prop="type" label="字段类型" align="center" />
<el-table-column prop="length" label="字段长度" align="center" />
<el-table-column prop="description" label="描述" align="center" />
<el-table-column prop="status" label="状态" align="center" />
<el-table-column :label="操作" align="center">
<template slot-scope="{row}">
<el-button type="text" @click="editor(row)">编辑</el-button>
<el-button type="text" @click="deleteAttribute(row)">删除</el-button>
</template>
</el-table-column>
</el-table>
- 在 < el-table > 中绑定数据 :data="tableData" tableData 为后台接口返回的数组
- 这里没什么和平时特殊的,主要是在方法中。
mounted中:
mounted() {
// 拖拽事件
this.column()
},
- 拖拽事件一定要放在 mounted 生命周期内,因为这时真实的DOM才渲染出来
methods中:
// 拖拽排序
column() {
const that = this
// 获取对象
const el = document.querySelector('.el-table__body-wrapper tbody')
// 设置配置
var ops = {
// 丝滑拖拽
animation: 1000,
onEnd({ newIndex, oldIndex }) {
// 获取拖动后的排序
const currRow = that.tableData.splice(oldIndex, 1)[0]
that.tableData.splice(newIndex, 0, currRow)
// 创建新数组
const tableArray = []
that.tableData.forEach((item) => {
tableArray.push(item.id)
})
// 调用排序接口
that.getSort(tableArray)
}
}
// 初始化
Sortable.create(el, ops)
},
- animation:动画是丝滑拖拽的关键,用户体验会更好一些,不然连续多次拖拽后眼睛会累。
- onEnd({ newIndex, oldIndex }) :是官网提供的方法,
- newIndex:返回拖拽后的下标。
- oldIndex:返回拖拽前的小标。
总结:
官网提供的方法样例中都需要设置data-id的值,而小编是后台返回的数据,在每条返回数据中加新的属性怕对后期有所影响,也有些麻烦。所以采用了这种不需要添加任何属性的方法。也很好理解。