vue使用dragstart等方法,实现拖拽排序

2020-05-06  本文已影响0人  plum_meizi

效果如图:


GIF.gif

代码:

<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>
上一篇 下一篇

猜你喜欢

热点阅读