效果如图:
代码:
<ul class="img-group">
<li
class="img-group-item"
v-for="(i,ind) in goodsDetail"
draggable="true"
:data-index="ind"
@dragstart.stop="dragstart($event,goodsDetail)"
@dragenter.stop="dragenter"
@dragover="dragover"
@dragend="dragend($event,changeSort)"
>
<img
:src="i"
class="pointer"
>
<i
class="delete-icon"
></i>
</li>
</ul>
draggable="true",使元素可拖拽
把方法提出来做成公共方法使用,命名drag.js
export default {
data() {
return {
currList: [],
startIndex: '',
enterIndex: '',
}
},
methods: {
dragstart(e, list) {
this.currList = list;
this.startIndex = e.target.getAttribute('data-index') || e.target.parentNode.getAttribute('data-index');
},
dragenter(e) {
this.enterIndex = e.target.getAttribute('data-index') || e.target.parentNode.getAttribute('data-index');
},
dragover(e) {
},
dragend(e, callback) {
// 交换位置
// this.currList[this.enterIndex] = this.currList.splice(this.startIndex, 1, this.currList[this.enterIndex])[0];
// 按顺序排序
if (this.enterIndex < this.startIndex) { // 拖动图片到前面
this.currList.splice(this.enterIndex, 0, this.currList[this.startIndex]);
this.currList.splice(Number(this.startIndex) + 1, 1);
} else { // 拖动图片到后面
this.currList.splice(Number(this.enterIndex) + 1, 0, this.currList[this.startIndex]);
this.currList.splice(Number(this.startIndex), 1);
}
this.startIndex = '';
e.preventDefault(); // 设置为可以被拖放
if (callback) {
callback();
}
}
}
}
引入js:import Drag from './drag.js'; mixins: [Drag],
<script>
import Drag from './drag.js';
export default {
mixins: [Drag],
methods: {
changeSort() {
// console.log(this.currList);
// 交换位置之后回调
},
}
}
</script>