这是自定义指令式实现的,el-table行拖动排序功能。下边我直接粘贴出来代码
先安装 npm i sortablejs
1.创建 Tablerowdrag.js 文件,加入以下代码。
/***
* 表格行拖动
* <el-table
:data="tableData"
row-key="id" //必须绑定数据的唯一标识,(!!!不能用数组下标)
v-tablerowdrag="tableData" //绑定的数据需要传,和data传值相同即可
>
tableData: [
{
id: 1,
name: "张三",
age: 10,
},
{
id: 2,
name: "王服",
age: 120,
},
],
*/
const {Sortable} = require('sortablejs'); //模块中引入,使用import会报错
module.exports={
inserted:(el,binding,vnode)=>{
const _this = vnode.context;
const tableData=binding.value //表格数据
const tbody =el.getElementsByTagName('tbody')[0]
Sortable.create(tbody, {
onEnd({ newIndex, oldIndex }) {
const currRow = tableData.splice(oldIndex, 1)[0];
tableData.splice(newIndex, 0, currRow);
},
});
}
}
2. main.js 里边注册自定义指令
import Tablerowdrag from "./customInstruction/Tablerowdrag.js" //路径换成自己的路径
//设置 v-tablerowdrag 表格行拖动排序-自定义指令
Vue.directive("tablerowdrag", Tablerowdrag);
3. vue组件中
<template>
<div class="r">
<el-table
:data="tableData"
border
width="100%"
row-key="id"
v-tablerowdrag="tableData"
>
<el-table-column width="60px" label="序号" type="index">
</el-table-column>
<el-table-column width="60px" label="姓名" prop="name"> </el-table-column>
<el-table-column width="60px" label="年纪" prop="age"> </el-table-column>
</el-table>
<el-button @click="push">增加一行数据</el-button>
</div>
</template>
<script>
export default {
name: "r",
components: {},
props: {},
data() {
return {
tableData: [
{
id: 1,
name: "张三",
age: 10,
},
{
id: 2,
name: "王服",
age: 120,
},
{
id: 3,
name: "荷叶",
age: 102,
},
{
id: 4,
name: "跳水",
age: 150,
},
],
};
},
computed: {},
watch: {},
created() {},
mounted() {},
methods: {
push() {
this.tableData.push({
id: this.tableData.length + 1,
name: "跳水",
age: 150 + this.tableData.length + 1,
});
},
},
};
</script>
<style scoped></style>
下边是演示,张三的位置改变了