Vue自定義菜單排序(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>

vue部分

<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>

 有用別忘了推薦喲!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM