Giter Site home page Giter Site logo

sortablejs / vue.draggable Goto Github PK

View Code? Open in Web Editor NEW
19.7K 19.7K 2.9K 14.8 MB

Vue drag-and-drop component based on Sortable.js

Home Page: https://sortablejs.github.io/Vue.Draggable/

License: MIT License

JavaScript 55.36% Vue 44.09% HTML 0.56%
component drag-and-drop vue

vue.draggable's Introduction

Sortable   Financial Contributors on Open Collective CircleCI DeepScan grade npm

Sortable is a JavaScript library for reorderable drag-and-drop lists.

Demo: http://sortablejs.github.io/Sortable/

Features

  • Supports touch devices and modern browsers (including IE9)
  • Can drag from one list to another or within the same list
  • CSS animation when moving items
  • Supports drag handles and selectable text (better than voidberg's html5sortable)
  • Smart auto-scrolling
  • Advanced swap detection
  • Smooth animations
  • Multi-drag support
  • Support for CSS transforms
  • Built using native HTML5 drag and drop API
  • Supports
  • Supports any CSS library, e.g. Bootstrap
  • Simple API
  • Support for plugins
  • CDN
  • No jQuery required (but there is support)
  • Typescript definitions at @types/sortablejs

Articles


Getting Started

Install with NPM:

npm install sortablejs --save

Install with Bower:

bower install --save sortablejs

Import into your project:

// Default SortableJS
import Sortable from 'sortablejs';

// Core SortableJS (without default plugins)
import Sortable from 'sortablejs/modular/sortable.core.esm.js';

// Complete SortableJS (with all plugins)
import Sortable from 'sortablejs/modular/sortable.complete.esm.js';

Cherrypick plugins:

// Cherrypick extra plugins
import Sortable, { MultiDrag, Swap } from 'sortablejs';

Sortable.mount(new MultiDrag(), new Swap());


// Cherrypick default plugins
import Sortable, { AutoScroll } from 'sortablejs/modular/sortable.core.esm.js';

Sortable.mount(new AutoScroll());

Usage

<ul id="items">
	<li>item 1</li>
	<li>item 2</li>
	<li>item 3</li>
</ul>
var el = document.getElementById('items');
var sortable = Sortable.create(el);

You can use any element for the list and its elements, not just ul/li. Here is an example with divs.


Options

var sortable = new Sortable(el, {
	group: "name",  // or { name: "...", pull: [true, false, 'clone', array], put: [true, false, array] }
	sort: true,  // sorting inside list
	delay: 0, // time in milliseconds to define when the sorting should start
	delayOnTouchOnly: false, // only delay if user is using touch
	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
	easing: "cubic-bezier(1, 0, 0, 1)", // Easing for animation. Defaults to null. See https://easings.net/ for examples.
	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

	dataIdAttr: 'data-id', // HTML attribute that is used by the `toArray()` method

	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

	swapThreshold: 1, // Threshold of the swap zone
	invertSwap: false, // Will always use inverted swap zone if set to true
	invertedSwapThreshold: 1, // Threshold of the inverted swap zone (will be set to swapThreshold value by default)
	direction: 'horizontal', // Direction of Sortable (will be detected automatically if not given)

	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.

	dragoverBubble: false,
	removeCloneOnHide: true, // Remove the clone element when it is not showing, rather than just hiding it
	emptyInsertThreshold: 5, // px, distance mouse must be from empty sortable to insert drag element into it


	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 is unchosen
	onUnchoose: function(/**Event*/evt) {
		// same properties as onEnd
	},

	// 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
		evt.oldDraggableIndex; // element's old index within old parent, only counting draggable elements
		evt.newDraggableIndex; // element's new index within new parent, only counting draggable elements
		evt.clone // the clone element
		evt.pullMode;  // when item is in another sortable: `"clone"` if cloning, `true` if moving
	},

	// 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: https://jsbin.com/nawahef/edit?js,output
		evt.dragged; // dragged HTMLElement
		evt.draggedRect; // DOMRect {left, top, right, bottom}
		evt.related; // HTMLElement on which have guided
		evt.relatedRect; // DOMRect
		evt.willInsertAfter; // Boolean that is true if Sortable will insert drag element after target by default
		originalEvent.clientY; // mouse position
		// return false; — for cancel
		// return -1; — insert before target
		// return 1; — insert after target
		// return true; — keep default insertion point based on the direction
		// return void; — keep default insertion point based on the direction
	},

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

	// Called when dragging element changes position
	onChange: function(/**Event*/evt) {
		evt.newIndex // most likely why this event is used is to get the dragging element's current index
		// same properties as onEnd
	}
});

group option

To drag elements from one list into another, both lists must have the same group value. You can also define whether lists can give away, give and keep a copy (clone), and receive elements.

  • name: String — group name
  • pull: true|false|["foo", "bar"]|'clone'|function — ability to move from the list. clone — copy the item, rather than move. Or an array of group names which the elements may be put in. Defaults to true.
  • put: true|false|["baz", "qux"]|function — whether elements can be added from other lists, or an array of group names from which elements can be added.
  • revertClone: boolean — revert cloned element to initial position after moving to a another list.

Demo:


sort option

Allow sorting inside list.

Demo: https://jsbin.com/jayedig/edit?js,output


delay option

Time in milliseconds to define when the sorting should start. Unfortunately, due to browser restrictions, delaying is not possible on IE or Edge with native drag & drop.

Demo: https://jsbin.com/zosiwah/edit?js,output


delayOnTouchOnly option

Whether or not the delay should be applied only if the user is using touch (eg. on a mobile device). No delay will be applied in any other case. Defaults to false.


swapThreshold option

Percentage of the target that the swap zone will take up, as a float between 0 and 1.

Read more

Demo: http://sortablejs.github.io/Sortable#thresholds


invertSwap option

Set to true to set the swap zone to the sides of the target, for the effect of sorting "in between" items.

Read more

Demo: http://sortablejs.github.io/Sortable#thresholds


invertedSwapThreshold option

Percentage of the target that the inverted swap zone will take up, as a float between 0 and 1. If not given, will default to swapThreshold.

Read more


direction option

Direction that the Sortable should sort in. Can be set to 'vertical', 'horizontal', or a function, which will be called whenever a target is dragged over. Must return 'vertical' or 'horizontal'.

Read more

Example of direction detection for vertical list that includes full column and half column elements:

Sortable.create(el, {
	direction: function(evt, target, dragEl) {
		if (target !== null && target.className.includes('half-column') && dragEl.className.includes('half-column')) {
			return 'horizontal';
		}
		return 'vertical';
	}
});

touchStartThreshold option

This option is similar to fallbackTolerance option.

When the delay option is set, some phones with very sensitive touch displays like the Samsung Galaxy S8 will fire unwanted touchmove events even when your finger is not moving, resulting in the sort not triggering.

This option sets the minimum pointer movement that must occur before the delayed sorting is cancelled.

Values between 3 to 5 are good.


disabled options

Disables the sortable if set to true.

Demo: https://jsbin.com/sewokud/edit?js,output

var sortable = Sortable.create(list);

document.getElementById("switcher").onclick = function () {
	var state = sortable.option("disabled"); // get

	sortable.option("disabled", !state); // set
};

handle option

To make list items draggable, Sortable disables text selection by the user. That's not always desirable. To allow text selection, define a drag handler, which is an area of every list element that allows it to be dragged around.

Demo: https://jsbin.com/numakuh/edit?html,js,output

Sortable.create(el, {
	handle: ".my-handle"
});
<ul>
	<li><span class="my-handle">::</span> list item text one
	<li><span class="my-handle">::</span> list item text two
</ul>
.my-handle {
	cursor: move;
	cursor: -webkit-grabbing;
}

filter option

Sortable.create(list, {
	filter: ".js-remove, .js-edit",
	onFilter: function (evt) {
		var item = evt.item,
			ctrl = evt.target;

		if (Sortable.utils.is(ctrl, ".js-remove")) {  // Click on remove button
			item.parentNode.removeChild(item); // remove sortable item
		}
		else if (Sortable.utils.is(ctrl, ".js-edit")) {  // Click on edit link
			// ...
		}
	}
})

ghostClass option

Class name for the drop placeholder (default sortable-ghost).

Demo: https://jsbin.com/henuyiw/edit?css,js,output

.ghost {
  opacity: 0.4;
}
Sortable.create(list, {
  ghostClass: "ghost"
});

chosenClass option

Class name for the chosen item (default sortable-chosen).

Demo: https://jsbin.com/hoqufox/edit?css,js,output

.chosen {
  color: #fff;
  background-color: #c00;
}
Sortable.create(list, {
  delay: 500,
  chosenClass: "chosen"
});

forceFallback option

If set to true, the Fallback for non HTML5 Browser will be used, even if we are using an HTML5 Browser. This gives us the possibility to test the behaviour for older Browsers even in newer Browser, or make the Drag 'n Drop feel more consistent between Desktop , Mobile and old Browsers.

On top of that, the Fallback always generates a copy of that DOM Element and appends the class fallbackClass defined in the options. This behaviour controls the look of this 'dragged' Element.

Demo: https://jsbin.com/sibiput/edit?html,css,js,output


fallbackTolerance option

Emulates the native drag threshold. Specify in pixels how far the mouse should move before it's considered as a drag. Useful if the items are also clickable like in a list of links.

When the user clicks inside a sortable element, it's not uncommon for your hand to move a little between the time you press and the time you release. Dragging only starts if you move the pointer past a certain tolerance, so that you don't accidentally start dragging every time you click.

3 to 5 are probably good values.


dragoverBubble option

If set to true, the dragover event will bubble to parent sortables. Works on both fallback and native dragover event. By default, it is false, but Sortable will only stop bubbling the event once the element has been inserted into a parent Sortable, or can be inserted into a parent Sortable, but isn't at that specific time (due to animation, etc).

Since 1.8.0, you will probably want to leave this option as false. Before 1.8.0, it may need to be true for nested sortables to work.


removeCloneOnHide option

If set to false, the clone is hidden by having it's CSS display property set to none. By default, this option is true, meaning Sortable will remove the cloned element from the DOM when it is supposed to be hidden.


emptyInsertThreshold option

The distance (in pixels) the mouse must be from an empty sortable while dragging for the drag element to be inserted into that sortable. Defaults to 5. Set to 0 to disable this feature.

Demo: https://jsbin.com/becavoj/edit?js,output

An alternative to this option would be to set a padding on your list when it is empty.

For example:

ul:empty {
  padding-bottom: 20px;
}

Warning: For :empty to work, it must have no node inside (even text one).

Demo: https://jsbin.com/yunakeg/edit?html,css,js,output


Event object (demo)

  • to:HTMLElement — list, in which moved element
  • from:HTMLElement — previous list
  • item:HTMLElement — dragged element
  • clone:HTMLElement
  • oldIndex:Number|undefined — old index within parent
  • newIndex:Number|undefined — new index within parent
  • oldDraggableIndex: Number|undefined — old index within parent, only counting draggable elements
  • newDraggableIndex: Number|undefined — new index within parent, only counting draggable elements
  • pullMode:String|Boolean|undefined — Pull mode if dragging into another sortable ("clone", true, or false), otherwise undefined

move event object

  • to:HTMLElement
  • from:HTMLElement
  • dragged:HTMLElement
  • draggedRect:DOMRect
  • related:HTMLElement — element on which have guided
  • relatedRect:DOMRect
  • willInsertAfter:Booleantrue if will element be inserted after target (or false if before)

Methods

option(name:String[, value:*]):*

Get or set the option.

closest(el:HTMLElement[, selector:String]):HTMLElement|null

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

toArray():String[]

Serializes the sortable's item data-id's (dataIdAttr option) into an array of string.

sort(order:String[], useAnimation:Boolean)

Sorts the elements according to the array.

var order = sortable.toArray();
sortable.sort(order.reverse(), true); // apply
save()

Save the current sorting (see store)

destroy()

Removes the sortable functionality completely.


Store

Saving and restoring of the sort.

<ul>
	<li data-id="1">order</li>
	<li data-id="2">save</li>
	<li data-id="3">restore</li>
</ul>
Sortable.create(el, {
	group: "localStorage-example",
	store: {
		/**
		 * Get the order of elements. Called once during initialization.
		 * @param   {Sortable}  sortable
		 * @returns {Array}
		 */
		get: function (sortable) {
			var order = localStorage.getItem(sortable.options.group.name);
			return order ? order.split('|') : [];
		},

		/**
		 * Save the order of elements. Called onEnd (when the item is dropped).
		 * @param {Sortable}  sortable
		 */
		set: function (sortable) {
			var order = sortable.toArray();
			localStorage.setItem(sortable.options.group.name, order.join('|'));
		}
	}
})

Bootstrap

Demo: https://jsbin.com/visimub/edit?html,js,output

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"/>


<!-- Latest Sortable -->
<script src="http://SortableJS.github.io/Sortable/Sortable.js"></script>


<!-- Simple List -->
<ul id="simpleList" class="list-group">
	<li class="list-group-item">This is <a href="http://SortableJS.github.io/Sortable/">Sortable</a></li>
	<li class="list-group-item">It works with Bootstrap...</li>
	<li class="list-group-item">...out of the box.</li>
	<li class="list-group-item">It has support for touch devices.</li>
	<li class="list-group-item">Just drag some elements around.</li>
</ul>

<script>
    // Simple list
    Sortable.create(simpleList, { /* options */ });
</script>

Static methods & properties

Sortable.create(el:HTMLElement[, options:Object]):Sortable

Create new instance.


Sortable.active:Sortable

The active Sortable instance.


Sortable.dragged:HTMLElement

The element being dragged.


Sortable.ghost:HTMLElement

The ghost element.


Sortable.clone:HTMLElement

The clone element.


Sortable.get(element:HTMLElement):Sortable

Get the Sortable instance on an element.


Sortable.mount(plugin:...SortablePlugin|SortablePlugin[])

Mounts a plugin to Sortable.


Sortable.utils
  • on(el:HTMLElement, event:String, fn:Function) — attach an event handler function
  • off(el:HTMLElement, event:String, fn:Function) — remove an event handler
  • css(el:HTMLElement):Object — get the values of all the CSS properties
  • css(el:HTMLElement, prop:String):Mixed — get the value of style properties
  • css(el:HTMLElement, prop:String, value:String) — set one CSS properties
  • css(el:HTMLElement, props:Object) — set more CSS properties
  • find(ctx:HTMLElement, tagName:String[, iterator:Function]):Array — get elements by tag name
  • bind(ctx:Mixed, fn:Function):Function — Takes a function and returns a new one that will always have a particular context
  • is(el:HTMLElement, selector:String):Boolean — check the current matched set of elements against a selector
  • closest(el:HTMLElement, selector:String[, ctx:HTMLElement]):HTMLElement|Null — for each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree
  • clone(el:HTMLElement):HTMLElement — create a deep copy of the set of matched elements
  • toggleClass(el:HTMLElement, name:String, state:Boolean) — add or remove one classes from each element
  • detectDirection(el:HTMLElement):String — automatically detect the direction of the element as either 'vertical' or 'horizontal'
  • index(el:HTMLElement, selector:String):Number — index of the element within its parent for a selected set of elements
  • getChild(el:HTMLElement, childNum:Number, options:Object, includeDragEl:Boolean):HTMLElement — get the draggable element at a given index of draggable elements within a Sortable instance
  • expando:String — expando property name for internal use, sortableListElement[expando] returns the Sortable instance of that elemenet

Plugins

Extra Plugins (included in complete versions)

Default Plugins (included in default versions)


CDN

<!-- jsDelivr :: Sortable :: Latest (https://www.jsdelivr.com/package/npm/sortablejs) -->
<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>

Contributing (Issue/PR)

Please, read this.


Contributors

Code Contributors

This project exists thanks to all the people who contribute. [Contribute].

Financial Contributors

Become a financial contributor and help us sustain our community. [Contribute]

Individuals

Organizations

Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]

MIT LICENSE

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

vue.draggable's People

Contributors

adamniederer avatar adrlen avatar blackmiaool avatar cgarnier avatar chinesedfan avatar david-desmaisons avatar dependabot[bot] avatar dominiczaq avatar eele94 avatar eskwayrd avatar hugome avatar jonathan-bird avatar jonathanrevell avatar jordanlev avatar keimeno avatar kolyaraketa avatar lcetinsoy avatar nkanaev avatar nlochschmidt avatar qnguyen12 avatar rasmustaarnby avatar robertoentringer avatar rudyonrails avatar thadavos avatar titpetric avatar tomlankhorst avatar vmitchell85 avatar y4roc avatar yukukotani avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue.draggable's Issues

Disable draggable on an item

Hi,

How can i disable the drag and drop effect on a specific item ?

I'm not sure but i didn't see any options to do that, maybe it's a feature to develop :)

Thanks by advance.

How to properly clone between Draggable

Hello, I've got 2 draggable components, from the first one objects can be cloned into the second draggable component. The problem Arises when cloning two object of the same type because they become interlinked (and changing data on one changes the data on the other) Is there a way to do a deep clone of one item?

Unable to override an event or get the event variable

I need to get the event variable on onUpdate event in the component where I'm using the draggable component, but overriding the onUpdate method doesn't work, not sure why.

<template>
<draggable :list="locations" :options="draggableOptions">
    <li v-for="location in locations">
        {{ location.name }}
    </li>
</draggable>
</template>

<script>
    import draggable from 'vuedraggable';
    export default {

        components: {
            draggable,
        },

        data() {
            return{
                locations: [
                    {id: 1, name: "location1"},
                    {id: 2, name: "location2"},
                    {id: 3, name: "location3"}
                ],
                draggableOptions: {
                    onUpdate: function (event) {
                        console.log(event); // never executed
                    },
                },
            }
        },
    }
</script>

How can I get the event variable from my component after update the list sorting? After move an item to another position, I need its id, evt.oldIndex and evt.newIndex.

Issues using Vue.Draggable + Vuex

Hi, I'm trying to implement an application that uses Vue.Draggable to sort a collection that is stored in a Vuex store.

The problem is related to the DOM modifications Vue.Draggable / SortableJS does. Is there any way to disable this behaviour and let Vuex reorganize the DOM from the state?

P.D: I attach a jsfiddle with the Vue.Draggable example that shows my problem.

https://jsfiddle.net/sqssmhtz/15/

Thanks for your help!

change made in v2.02 seem fatal in vuejs component of a Laravel 5.3 project

Now, no error on compile with gulp... but not working anymore...

The change made in v2.02 seem fatal for me...

I notice you change install
I have tried to use in my component like this

<script type="text/babel">
    import draggable from 'vuedraggable'
    export default {
        components: [draggable],
....

=> no error, but drag n drop not working

i haved tried without component section => no error but not working

I have tried to use with old method:

import VueDraggable from 'vuedraggable'
Vue.use(VueDraggable)

=> Error message when component start on webpage and not working.

So, i'm back to v2.01 version and i have apply the workaround of cgarnier.
=> works fine.

Allow or document use of Sortable events

I'm trying to set up my Sortable options like so:
sortableOptions: { draggable : ".list-item", onUpdate : function() { console.log('updated!'); } }
The onUpdate doesn't trigger though, since your version of the function overrides it during your _merge.

Is there a different way you suggest me hooking into that event so that I can also use it to execute some code? Or can it be updated to call your function, then the one passed through in an option?

Thanks!

I find your examples have wrong script src

For example, in examples/index.html

  1. There doesn't exist vue.js in your repository, so <script type="text/javascript" src="..\libs\vue\dist\vue.js"></script> is wrong;
  2. <script type="text/javascript" src="..\libs\Sortable\Sortable.js"></script> should be replace with <script type="text/javascript" src="libs\Sortable\Sortable.js"></script>;
  3. <script type="text/javascript" src="src\vuedraggable.js"></script> should be replace with <script type="text/javascript" src="../src\vuedraggable.js"></script>.

Is it possible to use Draggable Component with Vuejs transistion-group?

Hello, first and foremost, thanks for the great Vuejs component, it is very useful!

Now to my issue. If I use the draggable component outside the transition-group tag I don't get a Vuejs error but the entire group of list items is draggable instead of each individual list item. Please see the code below:

<draggable element="div" :list="machine.jobs" :options="draggableOptions">
   <transition-group name="list-complete">
      <div v-for="(job, index) in machine.jobs" 
              v-bind:key="job.jobNumber"
              class="list-complete-item" 
       >
         <b>{{ job.jobNumber }}</b>
       </div>
   </transition-group>
</draggable>

If I try to use the draggable component within the transition-group tag I get a Vue error stating that the children must be keyed. This is understandable seeing as the draggable element does not have a unique key and the documentation states that all elements within the transition-group must be uniquely keyed.

Can I use the draggable component with Vuejs transition-group feature? Am I missing something in my code that would allow this combination? If not, is this a feature that can be added to the draggable component in the future?

Make Vue.Dragable.For compatible with vuejs 2.0

I'm getting the following error: TypeError: dragableForDirective is undefined.
The relevant line in the traceback seems to be this one:

  • buildVueDragFor/vueDragFor.install() build.js line 1340 > eval:53

This happens just after Vue.use(VueDragableFor).
Is there any information you'd like me to add?

v-for component props

When using v-for on components and sending props to the component, the visual outputs don't display the new order but the Vue data property keeps the new order.

I believe, the indexing and element properties are getting mixed up somewhere. If you move an item between lists then the visual display items are incorrectly labeled but the Vue data is correct. (Edit:) Try moving John below Joao, then move Joao to the next list - you will then see John in the second list (in the grey area).

JSFiddle: https://jsfiddle.net/hellozach/31nqy8dp/

Properly spell "Draggable"

Maybe you're aware already, but "dragable" is a misspelling and is used throughout this package. When I was setting it up, it took me a little while to figure out why my 'v-draggable-for' directive wasn't working, but it was because I hadn't noticed the misspelling.

Feel free to reject this if it's not a concern, especially since updating it would be a breaking change, but I wanted to point it out just in case.

Thanks!

view model and view not syncing

Hi David,

i have a problem with the syncing to the model. I tested v-dragable-for with

data: {
    list:[
        {name:"John"},
        {name:"Joao"},
        {name:"Jean"}
    ]

which works fine. It is a Array of objects. Now my Model is not a Array of objects. It is a Object of Objects.

Then the syncing to the view doesn't work. Here is how i get my Questiongroups:

getQuestiongroups: function(){
    this.$http.get('admin/osamaker/api/group/get')
    .then(function (data){
        this.$set('questiongroups', data.data);
    })
    .catch(function (err){
        console.log(err);
    });

The result is a Object with the name 'questiongroups'. Here is a Screenshot

bildschirmfoto 2016-07-29 um 12 08 48

now there is an empty questions-array in each questiongroup-object. I have a method where i create and save new questions to a questiongroup. After the saveAction is done the questiongroups-object looks like:

bildschirmfoto 2016-07-29 um 12 15 57

So now its Object(questiongroups) > Object(questiongroup) > Object(questions) > Object(question)

I want to reorder the Questions so that every key = "question_order" (marked red) gets the new $index. This doesnt work. The $index is not changing after draging/sorting the list.

So thats for the beginning. I will provide a jsfiddle as soon as possible :-)

edit: here is the promised jsfiddle
https://jsfiddle.net/38a9sq4t/

best regards,
Robin

How to cancel a drag?

@David-Desmaisons I want to cancel a drag if the http request that is triggered on the @Move event fails. I've tried returning false (as per documentation here), but the item is not returned to the initial position.

How can I do this? If it helps, I'm just building kanbas board, so basically if the API call fails, I'd like the task to remain on the correct column / list, so the user knows that the task status was not updated (eventually I'll show a popup with this as well).

Thanks,

I have issue with 2.3.0 and working fine with 2.2.0

Hello David,

The latest version of your lib produce theses message on my code:

Uncaught (in promise) Sortable: el must be HTMLElement, and not [object Comment]
Uncaught TypeError: Cannot read property 'length' of undefined(…)
Uncaught TypeError: Cannot read property 'length' of undefined(…)

<ul class="listeConnectees">

	<draggable :list="sourcefiltree" class="dropZone" :options="{group: 'elements', ghostClass: 'elementDeplace', animation:'150'}">
		<li v-for="element in sourcefiltree">{{ element.titre }}</li>
	</draggable>
</ul>
<ul class="listeConnectees">
	<draggable :list="destination" class="dropZone" :options="{group: 'elements', ghostClass: 'sortable-ghost', animation: '150'}">
		<li v-for="element in destination">{{ element.titre }}</li>
	</draggable>
</ul>

It's not easy to do a jsfeedle because it's in a component who it make ajax request to populate the two lists on beforeMount() event ...

Can you have idea about the reason of this bugs ???

Best regards
Dominique

Bug when compiled with gulp.

Hello,

First thing, thank you for this job of re-writing.

I have a problem to integrate you component in a project.

when i do npm install vuedraggable --save => i see the installation of your component and sortablejs v1.4.2
in "node_modules" folder => folders "vuedraggable" and "sortablejs" are present and containt files of each js components

but when i launch 'gulp'
i have a error:

Module not found: Error: Can\'t resolve \'Sortable\ in vuedraggable.min.js

glup seem looking for this files in theses folders:

[/usr/share/nginx/myproject/site/node_modules/vuedraggable/dist/node_modules] [/usr/share/nginx/myproject/site/node_modules/vuedraggable/node_modules] [/usr/share/nginx/myproject/site/node_modules/node_modules] [/usr/share/nginx/myproject/site/node_modules/Sortable] [/usr/share/nginx/myproject/site/node_modules/Sortable] [/usr/share/nginx/myproject/site/node_modules/Sortable.js] [/usr/share/nginx/myproject/site/node_modules/Sortable.json]

but not in good place:
/usr/share/nginx/myproject/site/node_modules/sortablejs/Sortable.js

same thing after i launch npm update

The only workaround i find is copy Sortable.js in "root folder" node_modules... not very beautiful...

I never have this issue with dragable-for. May be some path missing in package.json of vuedraggable component or elsewhere ???

Best regards, and, one more time, thank you for this job.

Busted on iOS

On iOS (Google Chrome & Safari) the touch events have interference with scrolling and it causes a flickering effect when you start pulling down the page.

Not sure if it is occurring on Android as well.

Failed in finding sortablejs

Hi friends,

This is a little problem, in the package.json file dependencies in "sortablejs": "^1.4.2", but in the vuedragablefor.js line 142 var Sortable = require("Sortablejs"); . Each time to move my project, always told cannot find 'Sortablejs'. I think it maybe case sensitive in OS.

Update the vue component on onAdd

Hello!

In our App, we need to make an xhr call to store the dropped element and getting back his "child" elements. I make it in the onAdd like this:

Vue.component('ha-page', {
    template: '#page-template',
    props: ['page'],
    methods: {
       onAdd: function (event) {
            var templateId = $(event.clone).data('template_id');
            self.$http.post('/groups', {template_id: templateId}).then(
                function (xhr) {
                    // Success
                    Vue.set(event.item, 'fields', xhr.body.group_fields);
                    Vue.set(event.item, 'id', xhr.body.group.id);
                    toastr.error('Group created.');
                },
                function (xhr) {
                    //Fail
                    toastr.error('Group creation fail.');

                }
            );
        }
    }
});

But this lines do not update the new element of the list:

Vue.set(event.item, 'fields', xhr.body.group_fields);
Vue.set(event.item, 'id', xhr.body.group.id);

Is there a fancy way to update the new Vue element dropped in the list ?

Thx!

webpack error

ERROR in ./~/vuedraggable/dist/vuedraggable.js
Module not found: Error: Cannot resolve module 'Sortable' in /Users/lzxb/Documents/zhima-admin-webapp/node_modules/vuedraggable/dist
 @ ./~/vuedraggable/dist/vuedraggable.js 202:4-204:6

Getting error when dynamically making multiple lists

Basically everything works fine when following the example step by step but when incorporating it based on my constraints getting errors.

Implemented as follows:

<template>
  <div id="req-wrap">
    <div class="drag">
      <template v-for="term in terms" :term="term">
          <h2>{{term.number}}</h2>
          <div class="dragArea" >
              <template v-dragable-for="course in term.term_items" options='{"group":"term_items"}'>
                  <p>{{course.name}}</p>
              </template>
           </div>
      </template>
    </div>
    </div>
  </div>
</template>

<script>
  import DegreePlans from '../../components/degreeplans.vue'

  export default {
    data: function() {
      return {
        terms: [{
      "number": 1,
      "term_items": [
        {
          "name": "REQ 101",
          "courses": [
            "REQ 101"
          ]
        },
        {
          "name": "Multiple Courses",
          "courses": [
            "REQ 102",
            "REQ 103"
          ]
        },
        {
          "name": "Wildcard Courses",
          "wildcards": [
            {
              "name": "Upper division",
              "rules": [
                {
                  "department_code": "REQ",
                  "match_string": "*",
                  "minimum_match_number": 300,
                  "maximum_match_number": 499,
                  "minimum_hours": 1,
                  "maximum_hours": 6,
                  "exclude": false
                }
              ]
            },
            {
              "name": "Lower Division",
              "rules": [
                {
                  "department_code": "REQ",
                  "match_string": "*",
                  "minimum_match_number": 0,
                  "maximum_match_number": 199,
                  "minimum_hours": 1,
                  "maximum_hours": 6,
                  "exclude": false
                }
              ]
            }
          ]
        }
      ]
    },
    {
      "number": 2,
      "term_items": [
        {
          "name": "REQ 201",
          "courses": [
            "REQ 101"
          ]
        },
        {
          "name": "Multiple Courses",
          "courses": [
            "REQ 202",
            "REQ 203"
          ]
        },
        {
          "name": "Wildcard Courses",
          "wildcards": [
            {
              "name": "Upper division",
              "rules": [
                {
                  "department_code": "REQ",
                  "match_string": "*",
                  "minimum_match_number": 300,
                  "maximum_match_number": 499,
                  "minimum_hours": 1,
                  "maximum_hours": 6,
                  "exclude": false
                }
              ]
            },
            {
              "name": "Lower Division",
              "rules": [
                {
                  "department_code": "REQ",
                  "match_string": "*",
                  "minimum_match_number": 0,
                  "maximum_match_number": 199,
                  "minimum_hours": 1,
                  "maximum_hours": 6,
                  "exclude": false
                }
              ]
            }
          ]
        }
      ]
    }]
      }
    },

    route: {
      activate: function() {
        this.$http.get('degree_plans', []).then(function(response) {
          console.log(response.data)
          this.name = response.data.name
          this.id = response.data.id
          this.terms = response.data.terms
        })
      }
    }
  }
</script>

This is how it displays on my browser:
screen shot 2016-10-28 at 11 11 43 am
Vue tools:
screen shot 2016-10-28 at 11 12 42 am

Console (errors):
screen shot 2016-10-28 at 11 12 55 am

Nested dragging may cause unexpected DOM change

Our app has two-level nested draggable items and has list defined/mapped.

When dragging an item in the inner list, sometimes the DOM may update incorrectly, and when it happens, the item being dragged will jump to the beginning of the list. The vue data, however, is correct/as expected. So it seems like the DOM is updated inconsistently w.r.t. the event, whereas the vue data is fine.

We tried to make a reproducible demo: https://jsfiddle.net/6sha4vv6/1/

Dragging Wildcard Courses x to the place of Multiple Courses x and release can cause the former to jump to the first position.

troubble in using vuex

if i use :list="list" but the list is come from state. that may course some proublems.

@end showing same value for From and To.

Hi there, im trying to make a card game, and if i use the "move" prop, i get a lot of events, so i see that @EnD exists, and it only trigger when u finish moving, but im having the following issue:

I have a component called Spot, so i have many spots where cards can be, in Spot component i use Draggable to drag and drop cards, in this case im using @EnD="moveCard" but see screenshots to understand what happen:

<template>
    <div id="container">
        <ul class="deck">
          <draggable :list="cards" :options="{group:'solitaire'}" @end="moveCard" :id="'spot-'+number" class="draggableArea">
            <card v-for="card in cards" :instance="card"></card>
          </draggable>
        </ul>
    </div>
</template>
<style scoped>
    #container{
        background-color:#90FF0E;
        border:1px solid #583BFF;
        width:130px;
        height:200px;
    }
    #container ul {
        display:table-cell;
        list-style-type:none;
    }
    #container ul li {
        position:relative;
        top:-12px;
    }
    .draggableArea {
      min-height: 100px;
      min-width: 100px;
      border:2px solid rgb(255,133,100);
    }
</style>
<script>

    import Card from './Card'
    import draggable from 'vuedraggable'

    export default{
        data(){
            return{

            }
        },
        components:{
                Card,
                draggable
        },
        props: ['cards','number'],
        methods: {
          moveCard: function (event) {
            console.log(event)
            window.Event.$emit('movement',this.generateMovementInstructions(event))
          },
          move: function (event) {
            return false
          },
          generateMovementInstructions: function (event) {
            return {
              //card: event,
              from: this.detectSpotNumber(event.from.id),
              to: this.detectSpotNumber(event.to.id)
            }
          },
          detectSpotNumber: function (string) {
              return parseInt(string.replace('spot-',''))
          }
        }
    }
</script>

Ok using that code, look to sequence of screen shots:

here we got a new game, the first spot with cards is the number 5, and at his right is number 6.
1

so i move the 7 to a right spot, and it shows From and To as left spot id.
2

and when i return it to left spot (5), it shows From and To as id of right spot.
3

so alaways it is using from and to as (origin value).. can someone help me?

Issue with v-if condition

Plugin doesn't seem to work when element has conditional statements (ie. v-if).

<img v-dragable-for="..." v-if="statement" :src="..." />

No console errors either, just doesn't render list.

v-dragable-for can't work in a child component

@David-Desmaisons
Hi my friend, today I tried the plug-in draggable. I find the problem that i will work perfect in a same html,like this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="https://npmcdn.com/vue/dist/vue.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/sortable/1.4.2/Sortable.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>
    <script type="text/javascript" src="https://cdn.rawgit.com/David-Desmaisons/Vue.Dragable.For/v1.0.3/src/vuedragablefor.js"></script>

  </head>
  <body>
    <div id="main">
        <h1>Vue Dragable For</h1>
        <div class="drag">
            <h2>Dragable v-dragable-for</h2>
            <div class="dragArea">
                <div v-dragable-for="element in list">{{element.name}}</div>
             </div>
         </div>
        <div class="normal">
            <h2>Normal v-for</h2>
            <div class="dragArea">
                <div v-for="element in list">{{element.name}}</div>
             </div>
         </div>
        <button @click="add">Add</button>
        <button @click="replace">Replace</button>
    </div>

<script>
var vm = new Vue({
  el: "#main",
  data: {
    list:[{name:"John"}, 
        {name:"Joao"}, 
        {name:"Jean"} ]
    },
  methods:{
      add: function(){
        this.list.push({name:'Juan'});
      },
      replace: function(){
        this.list=[{name:'Edgard'}]
      }
    }
});
</script>
  </body>
</html>

But when i use the plug as a child component, it will failed to write the list name.
Here is in App.vue

<template>
     <div id="main">
        <h1>Vue Dragable For</h1>
        <div class="drag">
            <h2>Dragable v-dragable-for</h2>
            <div class="dragArea">
                <div v-dragable-for="element in list">{{element.name}}</div>
             </div>
         </div>
        <div class="normal">
            <h2>Normal v-for</h2>
            <div class="dragArea">
                <div v-for="element in list">{{element.name}}</div>
             </div>
         </div>
    </div>
</template>

<script>

export default {
    name: 'App',
    data() {
        return {
            list: [
                {name: 'xioah1'},
                {name: 'xioah2'},
                {name: 'xioah3'}
            ]
        }
    }
}
</script>

And the result is this(I got the warn message:'vue.common.js:986[Vue warn]: Error when evaluating expression "element.name".'):

Vue Dragable For
Dragable v-dragable-for
Normal v-for
xioah1
xioah2
xioah3

You can find that i can't list all values in the array, i worry about that the original function of 'Vue.directive('for')' is not working.

Only require needed lodash modules

Great library, works better out of the box than vue-sortable in my opinion.

One improvement I think is to only required the needed lodash modules for your directive.

Now the entire lodash library is included (about 80kb minified):
var _ = require("lodash");

You could simply require the needed modules (about 21kb minified):
var _clone = require("lodash/clone");
var _merge = require("lodash/merge");
var _isString = require("lodash/isString");
var _each = require("lodash/each");

.. which would save about 60kb.

Doesn't create a dragging element for the inner component

I am creating a dashboard app with widgets and using Bootstrap for the responsive.

This is what I am doing:

        <div class="row">
          <draggable :list="widgets">
              <div v-for="(widget, index) in widgets" :class="'col-lg-' + widget.cols">
                <chart-widget :setting="widget" v-on:remove="removeWidget"></chart-widget>
              </div>
          </draggable>
        </div>

chart-widget is a component to show the widget. I wrap the chart-widget inside a col <div>. The dragging works, but it doesn't show a dragging element when I drag. The behavior looks like this: https://youtu.be/f1sAd5VDLeQ

How could I make this work?

Model not updating when using nested components

I have two nested components and when I drag one inner component to another outer component, only the view updating (with DOM manipulation I guess), the model stays the same.
How can I make the model update?

don't hard-code "div" as outer element

Currently, Vue.Draggable only allows to drag and drop div elements which get enclosed in an outer div. But sometimes, one might want to drag and drop li inside a ul or ol, or tr inside a tbody.

So, it would be nice if one could configure if a div element is created as outer element for the draggable objects, or something else like a ul or tbody.

Elements being set with "display: none"

I have an issue where one of my elements are being hidden. I have no idea how to debug the issue but I have confirmed it's related to :list="tabs" as if I removed that, it all works as expected.

Here is a portion of my template:

<draggable class="nav nav-tabs" :element="ul" :list="tabs">
    <li class="nav-item" v-for="tab in tabs">
        <a href="#" class="nav-link" :class="{ active: tab.active }" @click.prevent="selectTab(tab)">
            <i :class="tab.icon" v-if="tab.icon"></i>
            <span v-show="tab.options.showname">{{ tab.name }}</span>
            <span @click.prevent.stop="requestRemoveTab(tab)" v-if="tab.options.closeable">&times;</span>
        </a>
    </li>
</draggable>

Here is one of my tab creations that utilises all possible options:

this.createTab(`roomlist`, {
    icon: 'fa fa-plus',
    name: 'Rooms',
    component: 'roomlistTabView',
    active: true,
    options: {
        showname: false,
        closeable: false
    }
});

The result is that everything displays fine until I start dragging tabs around. What happens then is the second span element (containing &times;) is being hidden using the inline css display: none. I can confirm that the other elements are being displayed. Adding in :list="tabs" from what I know is optional in my case and it works just fine either way but the issue is with that, for sure.

If I'm also correct, v-if would not render the element unless it returns true so something strange is definitely going on there hence why I'm unsure how to debug it. Anyone know what might be going on?

onEnd event update does not reflect the newly sorted element in DOM

Current Action: I drag an item from one list to another list

Expected Result: onEnd of the item sort, the item should be shown in the DOM and VM state in the new dragged position

Current Result: onEnd of the item sort, the item is shown in the original DOM position as well as the VM state. It would then run a function to update it in the VM before the new changes are reflected are a later stage.

===

The current (example) scenario I have is I have 2 lists with 2 different IDs and within the lists there can be items that can be dragged from one list to another.

When I drag one item from one list to another, I call the 'onEnd' event to try to detect which list ID the item is dropped on, so that I can make an API call to update the position change on the database.

However, due to the DOM cancellation, during the 'onEnd' event (or any other event actually), I end up detecting the original list ID as the item will simply revert back to the original position and placement of the list before it was moved.

I don't see how I am able to detect the ID of the list when the user drops the item (ends the drag). I am able to detect it using the onMove event, however I am not sure if that's the base practice. What I would have to do then is to maintain the ID of the list in component state as the user drags it around, and only onEnd event do I read the component state and send it to the server.

Any suggestions would be welcomed!

Failed with npm install on OS X

Hi friend,
Today, I want to add the vueDraggablefor to my project, but i failed.

First i install the model :
123

And here is how to use:
2

I always failed in build the js, the console log tell me that: "Cannot find module 'vuedragablefor' from '/Users/wuxiaolian/Documents/workspace/121dian-activity/self-project/src'".
Why it find the 'src' folder, not the node_module folder?

Then i created a new project do then same actions, and i got the same results.
Do you have any idears? Thanks for your time.

don't work in multistage array

html:

<div id="main">
  <h1>Vue Dragable For</h1>
  <div v-for="item in list">
    <div v-dragable-for="element in item" options='{"group":"people"}'>{{element.name}}</div>
    <hr>
  </div>
</div>

js :

var vm = new Vue({
  el: "#main",
  data: {
    list: [
      [{
        name: "John"
      }, {
        name: "Joao"
      }, {
        name: "Jean"
      }],
      [{
        name: "Juan"
      }, {
        name: "Edgard"
      }, {
        name: "Johnson"
      }]
    ],
  },
  methods: {
    add: function() {
      this.list.push({
        name: 'Juan'
      });
    },
    replace: function() {
      this.list = [{
        name: 'Edgard'
      }]
    }
  }
});


Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.