1. 程式人生 > >vue拖拽排序外掛vuedraggable

vue拖拽排序外掛vuedraggable

首先在vue專案中,用npm包下載下來

npm install vuedraggable -S

下載下來後,引入外掛,在你的vue檔案的script標籤裡面這樣引入

import draggable from 'vuedraggable'

別忘了下面要註冊元件

components: {
    draggable
},

然後就可以在template標籤裡面使用了

單個元件

<draggable v-model="colors" @update="datadragEnd" :options = "{animation:500}">
            <transition-group>
                <div v-for="element in colors" :key="element.text" class = "drag-item">
                    {{element.text}}
                </div>
            </transition-group>
 </draggable>

2個元件左右結構

<el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="對外產品名稱">
                <el-input v-model="proAttribute.description" placeholder="對外產品名稱" style="width: 250px"></el-input>
              </el-form-item>
              <el-form-item label="對外產品屬性">
              <template>
                <draggable v-model="colors" @update="datadragEnd" :options = "{animation:500}">
                  <transition-group>
                    <div v-for="element in colors" :key="element.text" class = "drag-item">
                      {{element.text}}
                    </div>
                  </transition-group>
                </draggable>
              </template>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="對內產品名稱">
                <el-input v-model="proAttribute.description" placeholder="對內產品名稱" style="width: 250px"></el-input>
              </el-form-item>
              <el-form-item label="對內產品屬性">
              <template>
                <draggable v-model="colors" @update="datadragEnd" :options = "{animation:500}">
                  <transition-group>
                    <div v-for="element in colors" :key="element.text" class = "drag-item">
                      {{element.text}}
                    </div>
                  </transition-group>
                </draggable>
              </template>
              </el-form-item>
            </el-col>
          </el-row>

下面貼一下詳細用法

<template>
    <draggable v-model="colors" @update="datadragEnd" :options = "{animation:500}">
            <transition-group>
                <div v-for="element in colors" :key="element.text" class = "drag-item">
                    {{element.text}}
                </div>
            </transition-group>
    </draggable>
</template>

<script>
    import draggable from 'vuedraggable'
    export default{
        data(){
            return{
                msg:"這是測試元件",
                colors: [
                    {
                        text: "Aquamarine",
                    }, 
                    {
                        text: "Hotpink",
                    }, 
                    {
                        text: "Gold",
                    }, 
                    {
                        text: "Crimson",
                    }, 
                    {
                        text: "Blueviolet",
                    },
                    {
                        text: "Lightblue",
                    }, 
                    {
                        text: "Cornflowerblue",
                    }, 
                    {
                        text: "Skyblue",
                    }, 
                    {
                        text: "Burlywood",
                    }
                ],
                startArr:[],
                endArr:[],
                count:0,
            }
        },
        components: {
          draggable
        },
        methods:{
            getdata (evt) {
                console.log(evt.draggedContext.element.text)
            },
            datadragEnd (evt) {
                evt.preventDefault();
                console.log('拖動前的索引 :' + evt.oldIndex)
                console.log('拖動後的索引 :' + evt.newIndex)
                console.log(this.colors);
            }
        },
        mounted () {
	        //為了防止火狐瀏覽器拖拽的時候以新標籤開啟,此程式碼真實有效
            document.body.ondrop = function (event) {
                event.preventDefault();
                event.stopPropagation();
            }
        }
    }
</script>

<style lang="scss" scoped>
    .test{
        border:1px solid #ccc;
    }
    .drag-item{
        width: 200px;
        height: 50px;
        line-height: 50px;
        margin: auto;
        position: relative;
        background: #ddd;
        margin-top:20px;
    }
    .ghostClass{
        opacity: 1;
    }
    .bottom{
        width: 200px;
        height: 50px;
        position: relative;
        background: blue;
        top:2px;
        left: 2px;
        transition: all .5s linear;
    }
</style>

options配置如下

var sortable = new Sortable(el, {
	group: "name",  // or { name: "...", pull: [true, false, clone], put: [true, false, array] }
	sort: true,  // sorting inside list
	delay: 0, // time in milliseconds to define when the sorting should start
	touchStartThreshold: 0, // px, how many pixels the point should move before cancelling a delayed drag event
	disabled: false, // Disables the sortable if set to true.
	store: null,  // @see Store
	animation: 150,  // ms, animation speed moving items when sorting, `0` — without animation
	handle: ".my-handle",  // Drag handle selector within list items
	filter: ".ignore-elements",  // Selectors that do not lead to dragging (String or Function)
	preventOnFilter: true, // Call `event.preventDefault()` when triggered `filter`
	draggable: ".item",  // Specifies which items inside the element should be draggable
	ghostClass: "sortable-ghost",  // Class name for the drop placeholder
	chosenClass: "sortable-chosen",  // Class name for the chosen item
	dragClass: "sortable-drag",  // Class name for the dragging item
	dataIdAttr: 'data-id',

	forceFallback: false,  // ignore the HTML5 DnD behaviour and force the fallback to kick in

	fallbackClass: "sortable-fallback",  // Class name for the cloned DOM Element when using forceFallback
	fallbackOnBody: false,  // Appends the cloned DOM Element into the Document's Body
	fallbackTolerance: 0, // Specify in pixels how far the mouse should move before it's considered as a drag.

	scroll: true, // or HTMLElement
	scrollFn: function(offsetX, offsetY, originalEvent, touchEvt, hoverTargetEl) { ... }, // if you have custom scrollbar scrollFn may be used for autoscrolling
	scrollSensitivity: 30, // px, how near the mouse must be to an edge to start scrolling.
	scrollSpeed: 10, // px

	setData: function (/** DataTransfer */dataTransfer, /** HTMLElement*/dragEl) {
		dataTransfer.setData('Text', dragEl.textContent); // `dataTransfer` object of HTML5 DragEvent
	},

	// Element is chosen
	onChoose: function (/**Event*/evt) {
		evt.oldIndex;  // element index within parent
	},

	// Element dragging started
	onStart: function (/**Event*/evt) {
		evt.oldIndex;  // element index within parent
	},

	// Element dragging ended
	onEnd: function (/**Event*/evt) {
		var itemEl = evt.item;  // dragged HTMLElement
		evt.to;    // target list
		evt.from;  // previous list
		evt.oldIndex;  // element's old index within old parent
		evt.newIndex;  // element's new index within new parent
	},

	// Element is dropped into the list from another list
	onAdd: function (/**Event*/evt) {
		// same properties as onEnd
	},

	// Changed sorting within list
	onUpdate: function (/**Event*/evt) {
		// same properties as onEnd
	},

	// Called by any change to the list (add / update / remove)
	onSort: function (/**Event*/evt) {
		// same properties as onEnd
	},

	// Element is removed from the list into another list
	onRemove: function (/**Event*/evt) {
		// same properties as onEnd
	},

	// Attempt to drag a filtered element
	onFilter: function (/**Event*/evt) {
		var itemEl = evt.item;  // HTMLElement receiving the `mousedown|tapstart` event.
	},

	// Event when you move an item in the list or between lists
	onMove: function (/**Event*/evt, /**Event*/originalEvent) {
		// Example: http://jsbin.com/tuyafe/1/edit?js,output
		evt.dragged; // dragged HTMLElement
		evt.draggedRect; // TextRectangle {left, top, right и bottom}
		evt.related; // HTMLElement on which have guided
		evt.relatedRect; // TextRectangle
		originalEvent.clientY; // mouse position
		// return false; — for cancel
	},

	// Called when creating a clone of element
	onClone: function (/**Event*/evt) {
		var origEl = evt.item;
		var cloneEl = evt.clone;
	}
});