自定义菜单拖放(draggable属性)

代码简单 ,  给你们提供一个思路 

html部分

<template>
    <div>
        <ul>
            <li v-for="(item,index) in dataList" 
            :key="item.id" 
            draggable="true" 
            @dragstart="start(item,index)"
            @dragover="over($event)"
            @drop="drop(index)"
            v-text="item.text"></li>
        </ul>
    </div>
</template>

js部分

<script>
    export default {
        data(){
            return {
                currMoveItem : false,
                currMoveIndex : false,
                dataList : [
                    {
                        'text' : '数据1',
                        'id' : 1,
                    },
                    {
                        'text' : '数据2',
                        'id' : 2,
                    },
                    {
                        'text' : '数据3',
                        'id' : 3,
                    },
                    {
                        'text' : '数据4',
                        'id' : 4,
                    },
                    {
                        'text' : '数据5',
                        'id' : 5,
                    },
                ]
            }
        },
        methods:{
            start(item,index){
                this.currMoveItem = item; // 当前移动元素
                this.currMoveIndex = index; // 当前移动数组下标
                console.log('开始移动',item,index);
            },
            over(ev){
                ev.preventDefault();
            },
            drop(index){
                console.log('放下',index);
                if(index == this.currMoveIndex) return false; // 不是原地移动
            
                console.log('从'+this.currMoveIndex+'移动到'+index);
                this.dataList.splice(this.currMoveIndex,1); // 删除元素之前所在位置
                this.dataList.splice(index,0,this.currMoveItem); // 在需要放下元素的位置前插入移动元素
                // 下面有无都无所谓
                this.currMoveIndex = false;
                this.currMoveItem = false;
            }
        }
    }
</script>

css部分

<style>
    ul li {
        width: 150px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        margin: 10px;
        color: #FFF;
        background: #666666;
        list-style: none;
        cursor: pointer;
        float: left;
    }
</style>

猜你喜欢

转载自www.cnblogs.com/-wei/p/12980577.html
今日推荐