一、安装sortablejs
npm install sortablejs
二、全局注册sortablejs
import Sortable from "sortablejs";
window.$Sortable = Sortable;
三、页面内要拖拽的html内容
<div class="formBox">
<div class="bannerJson formBody" style="cursor: move">
<div v-for="(item, index) in form" :key="index">
</div>
</div>
</div>
四 、页面内JS方法
onMounted(() => {
rowDrag();
});
const rowDrag = () => {
let sortableInstance = null;
const tbody = document.querySelector(".formBox .formBody");
if (sortableInstance) {
sortableInstance.destroy();
}
sortableInstance = new $Sortable(tbody, {
filter: "input,textarea",
preventOnFilter: false,
disabled: false,
animation: 150,
dragClass: "drop-dragClass",
ghostClass: "drop-ghostClass",
chosenClass: "drop-chosenClass",
onEnd(evt) {
console.log("结束表格拖拽", `拖动前索引${evt.oldIndex}---拖动后索引${evt.newIndex}`);
let oldIndex = evt.oldIndex;
let newIndex = evt.newIndex;
if (oldIndex != newIndex) {
let form_news = JSON.parse(JSON.stringify(props.form));
let temp = form_news[oldIndex];
if (oldIndex < newIndex) {
for (let i = oldIndex; i < newIndex; i++) {
form_news[i] = form_news[i + 1];
}
} else if (oldIndex > newIndex) {
for (let i = oldIndex; i > newIndex; i--) {
form_news[i] = form_news[i - 1];
}
}
form_news[newIndex] = temp;
props.form = [];
nextTick(() => {
props.form= JSON.parse(JSON.stringify(form_news));
console.log(props.form, "form");
update();
});
}
}
});
};
五 、页面css样式优化
.drop-dragClass {
background: rgba(0, 105, 255, 0.3) !important;
border-radius: 10px;
}
.drop-ghostClass {
background: rgba(0, 105, 255, 0.8) !important;
border-radius: 10px;
}
.drop-chosenClass:hover > div {
background: rgba(0, 105, 255, 0.3) !important;
border-radius: 10px;
}
:deep(.el-link__inner) {
color: #0069ff;
}
#formBodyBox > div {
cursor: grab;
transition: all 0.3s ease;
}
#formBodyBox > div:hover {
background: #f1f3f5;
transform: translateX(5px);
}
#formBodyBox > div.sortable-drag {
opacity: 0.5;
transform: scale(0.98);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.sortable-placeholder {
background: #e9ecef;
border: 2px dashed #adb5bd;
border-radius: 6px;
margin: 8px 0;
height: 42px;
}
.sortable-ghost {
opacity: 0.7;
transform: rotate(3deg);
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}
.sortable-chosen {
background: #fff3bf !important;
border-color: #ffd43b !important;
}
#formBodyBox {
background: #f8f9fa;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
transition: background 0.3s;
border-radius: 4px;
}
#formBodyBox .sortable-active {
background: #f1f3f5;
}