sortablejs也支持不是表格的拖拽

概要

之前使用sortablejs都是拖拽表格,这次有个需求是直接拖拽div,发现原来也可以,就记录一下下

展示效果

在这里插入图片描述

代码展示

提示:sortablejs使用的版本是 "sortablejs": "^1.15.0",

<template>
   <div class="darg_label">
        <span class="darg-item"
        :title="item.name"
        v-for="item in list" :key="item.id">{{ item.name }}</span>
    </div>
</template>

<script>
import Sortable from 'sortablejs';
export default {
    data() {
        return {
           list: [{
            id: 1,
            name: '1'
           }, {
            id: 2,
            name: '2'
           }]
        }
    },

    activated() {
        this.sortTab()
    },
    methods: {
        sortTab() {
           // 获取需要拖拽节点的父节点
            const box = document.querySelector('.darg_label');
            console.log('box', box)
            // 创建拖拽实例
            Sortable.create(box, {
                animation: 150, // 动画
                handle: '.darg-item', // 需要拖拽的元素类名称
                // 开始拖动事件
                onStart: (e) => {
                console.log('开始拖动', e);
                },
                // 结束拖动事件
                onEnd: ({ newIndex, oldIndex }) => {
                    this.list.splice(newIndex, 0, this.list.splice(oldIndex, 1)[0]);
                    let newArray = this.list.slice(0);
                    this.list = [];
                    this.$nextTick(() => {
                    this.list = newArray
                });
            }
            });
        }
    }
};
</script>
<style lang="less" scoped>
 .darg-item {
    background: var(--td-brand-color-1);
    border-radius: 4px;
    color: var(--td-brand-color-6);
    padding: 8px 12px;
    margin: 10px 10px 0 0;
    cursor: pointer;
    display: inline-block;
}
.darg_label{
  margin-bottom:10px;
}
</style>

小结

提示:需要注意的点就是获取节点时必须是需要拖拽元素的父节点
有不足之处,请多多指教!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值