項目中要求可以拖拽element UI table 的表格
1隅熙、使用 sortablejs 插件
npm install sortablejs --save
2、引入
import Sortable from "sortablejs";
3核芽、直接上代碼
<template>
<div class="table">
<el-table
ref="dragTable"
:data="tableData"
border
:row-class-name="tableRowClassName"
>
<el-table-column prop="date" label="日期"></el-table-column>
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="address" label="地址"></el-table-column>
<el-table-column label="操作">
<template>
<el-button class="move" type="text" size="small">拖 拽</el-button>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
import Sortable from "sortablejs";
export default {
data() {
return {
tableData: [
{
id: "1",
name: "text_1",
date: "1111-11-11",
address: "測試_1",
},
{
id: "2",
name: "text_2_不可拖拽",
date: "2222-22-22",
address: "測試_2_不可拖拽",
disabled: true,
},
{
id: "3",
name: "text_3",
date: "3333-33-33",
address: "測試_3",
},
{
id: "4",
name: "text_4",
date: "4444-44-44",
address: "測試_4",
},
{
id: "5",
name: "text_5",
date: "5555-55-55",
address: "測試_5",
},
],
};
},
methods: {
// 創(chuàng)建sortable實例
initSortable() {
// 獲取表格row的父節(jié)點
const ele = this.$refs.dragTable.$el.querySelector(
".el-table__body > tbody"
);
// 創(chuàng)建拖拽實例
let dragTable = Sortable.create(ele, {
animation: 150, //動畫
disabled: false, // 拖拽不可用? false 啟用(剛剛渲染表格的時候起作用猛们,后面不起作用)
handle: ".move", //指定拖拽目標,點擊此目標才可拖拽元素(此例中設(shè)置操作按鈕拖拽)
filter: ".disabled", //指定不可拖動的類名(el-table中可通過row-class-name設(shè)置行的class)
dragClass: "dragClass", //設(shè)置拖拽樣式類名
ghostClass: "ghostClass", //設(shè)置拖拽湍螅靠樣式類名
chosenClass: "chosenClass", //設(shè)置選中樣式類名
// 開始拖動事件
onStart: () => {
console.log("開始拖動");
},
// 結(jié)束拖動事件
onEnd: ({ newIndex, oldIndex }) => {
console.log(
"結(jié)束拖動",
`拖動前索引${oldIndex}---拖動后索引${newIndex}`
);
const currRow = _this.tableData.splice(oldIndex, 1)[0];
this.tableData.splice(newIndex, 0, currRow);
},
});
},
// 設(shè)置表格row的class
tableRowClassName({ row }) {
if (row.disabled) {
return "disabled";
}
return "";
},
},
mounted() {
this.initSortable();
},
};
</script>
//注意如果加上scoped 樣式就可能不起作用
<style lang='scss'>
// 拖拽
.dragClass {
background: rgba($color: #41c21a, $alpha: 0.5) !important;
}
// 屯涮裕靠
.ghostClass {
background: rgba($color: #6cacf5, $alpha: 0.5) !important;
}
// 選擇
.chosenClass:hover > td {
background: rgba($color: #f56c6c, $alpha: 0.5) !important;
}
</style>