GithubHelp home page GithubHelp logo

sortablejs / vue.draggable Goto Github PK

View Code? Open in Web Editor NEW
19.8K 239.0 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%
drag-and-drop vue component

vue.draggable's Introduction

Vue.Draggable

CircleCI Coverage codebeat badge GitHub open issues npm download npm download per month npm version MIT License

Vue component (Vue.js 2.0) or directive (Vue.js 1.0) allowing drag-and-drop and synchronization with view model array.

Based on and offering all features of Sortable.js

For Vue 3

See vue.draggable.next

Demo

demo gif

Live Demos

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

https://david-desmaisons.github.io/draggable-example/

Features

  • Full support of Sortable.js features:
    • Supports touch devices
    • Supports drag handles and selectable text
    • Smart auto-scrolling
    • Support drag and drop between different lists
    • No jQuery dependency
  • Keeps in sync HTML and view model list
  • Compatible with Vue.js 2.0 transition-group
  • Cancellation support
  • Events reporting any changes when full control is needed
  • Reuse existing UI library components (such as vuetify, element, or vue material etc...) and make them draggable using tag and componentData props

Backers

Looking for backers!

Donate

Find this project useful? You can buy me a โ˜• or a ๐Ÿบ

paypal

Installation

With npm or yarn

yarn add vuedraggable

npm i -S vuedraggable

Beware it is vuedraggable for Vue 2.0 and not vue-draggable which is for version 1.0

with direct link

<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<!-- CDNJS :: Sortable (https://cdnjs.com/) -->
<script src="//cdn.jsdelivr.net/npm/[email protected]/Sortable.min.js"></script>
<!-- CDNJS :: Vue.Draggable (https://cdnjs.com/) -->
<script src="//cdnjs.cloudflare.com/ajax/libs/Vue.Draggable/2.20.0/vuedraggable.umd.min.js"></script>

cf example section

For Vue.js 2.0

Use draggable component:

Typical use:

<draggable v-model="myArray" group="people" @start="drag=true" @end="drag=false">
   <div v-for="element in myArray" :key="element.id">{{element.name}}</div>
</draggable>

.vue file:

  import draggable from 'vuedraggable'
  ...
  export default {
        components: {
            draggable,
        },
  ...

With transition-group:

<draggable v-model="myArray">
    <transition-group>
        <div v-for="element in myArray" :key="element.id">
            {{element.name}}
        </div>
    </transition-group>
</draggable>

Draggable component should directly wrap the draggable elements, or a transition-component containing the draggable elements.

With footer slot:

<draggable v-model="myArray" draggable=".item">
    <div v-for="element in myArray" :key="element.id" class="item">
        {{element.name}}
    </div>
    <button slot="footer" @click="addPeople">Add</button>
</draggable>

With header slot:

<draggable v-model="myArray" draggable=".item">
    <div v-for="element in myArray" :key="element.id" class="item">
        {{element.name}}
    </div>
    <button slot="header" @click="addPeople">Add</button>
</draggable>

With Vuex:

<draggable v-model='myList'>
computed: {
    myList: {
        get() {
            return this.$store.state.myList
        },
        set(value) {
            this.$store.commit('updateList', value)
        }
    }
}

Props

value

Type: Array
Required: false
Default: null

Input array to draggable component. Typically same array as referenced by inner element v-for directive.
This is the preferred way to use Vue.draggable as it is compatible with Vuex.
It should not be used directly but only though the v-model directive:

<draggable v-model="myArray">

list

Type: Array
Required: false
Default: null

Alternative to the value prop, list is an array to be synchronized with drag-and-drop.
The main difference is that list prop is updated by draggable component using splice method, whereas value is immutable.
Do not use in conjunction with value prop.

All sortable options

New in version 2.19

Sortable options can be set directly as vue.draggable props since version 2.19.

This means that all sortable option are valid sortable props with the notable exception of all the method starting by "on" as draggable component expose the same API via events.

kebab-case propery are supported: for example ghost-class props will be converted to ghostClass sortable option.

Example setting handle, sortable and a group option:

<draggable
        v-model="list"
        handle=".handle"
        :group="{ name: 'people', pull: 'clone', put: false }"
        ghost-class="ghost"
        :sort="false"
        @change="log"
      >
      <!-- -->
</draggable>

tag

Type: String
Default: 'div'

HTML node type of the element that draggable component create as outer element for the included slot.
It is also possible to pass the name of vue component as element. In this case, draggable attribute will be passed to the create component.
See also componentData if you need to set props or event to the created component.

clone

Type: Function
Required: false
Default: (original) => { return original;}

Function called on the source component to clone element when clone option is true. The unique argument is the viewModel element to be cloned and the returned value is its cloned version.
By default vue.draggable reuses the viewModel element, so you have to use this hook if you want to clone or deep clone it.

move

Type: Function
Required: false
Default: null

If not null this function will be called in a similar way as Sortable onMove callback. Returning false will cancel the drag operation.

function onMoveCallback(evt, originalEvent){
   ...
    // return false; โ€” for cancel
}

evt object has same property as Sortable onMove event, and 3 additional properties:

  • draggedContext: context linked to dragged element
    • index: dragged element index
    • element: dragged element underlying view model element
    • futureIndex: potential index of the dragged element if the drop operation is accepted
  • relatedContext: context linked to current drag operation
    • index: target element index
    • element: target element view model element
    • list: target list
    • component: target VueComponent

HTML:

<draggable :list="list" :move="checkMove">

javascript:

checkMove: function(evt){
    return (evt.draggedContext.element.name!=='apple');
}

See complete example: Cancel.html, cancel.js

componentData

Type: Object
Required: false
Default: null

This props is used to pass additional information to child component declared by tag props.
Value:

  • props: props to be passed to the child component
  • attrs: attrs to be passed to the child component
  • on: events to be subscribe in the child component

Example (using element UI library):

<draggable tag="el-collapse" :list="list" :component-data="getComponentData()">
    <el-collapse-item v-for="e in list" :title="e.title" :name="e.name" :key="e.name">
        <div>{{e.description}}</div>
     </el-collapse-item>
</draggable>
methods: {
    handleChange() {
      console.log('changed');
    },
    inputChanged(value) {
      this.activeNames = value;
    },
    getComponentData() {
      return {
        on: {
          change: this.handleChange,
          input: this.inputChanged
        },
        attrs:{
          wrap: true
        },
        props: {
          value: this.activeNames
        }
      };
    }
  }

Events

  • Support for Sortable events:

    start, add, remove, update, end, choose, unchoose, sort, filter, clone
    Events are called whenever onStart, onAdd, onRemove, onUpdate, onEnd, onChoose, onUnchoose, onSort, onClone are fired by Sortable.js with the same argument.
    See here for reference

    Note that SortableJS OnMove callback is mapped with the move prop

HTML:

<draggable :list="list" @end="onEnd">
  • change event

    change event is triggered when list prop is not null and the corresponding array is altered due to drag-and-drop operation.
    This event is called with one argument containing one of the following properties:

    • added: contains information of an element added to the array
      • newIndex: the index of the added element
      • element: the added element
    • removed: contains information of an element removed from to the array
      • oldIndex: the index of the element before remove
      • element: the removed element
    • moved: contains information of an element moved within the array
      • newIndex: the current index of the moved element
      • oldIndex: the old index of the moved element
      • element: the moved element

Slots

Limitation: neither header or footer slot works in conjunction with transition-group.

Header

Use the header slot to add none-draggable element inside the vuedraggable component. Important: it should be used in conjunction with draggable option to tag draggable element. Note that header slot will always be added before the default slot regardless its position in the template. Ex:

<draggable v-model="myArray" draggable=".item">
    <div v-for="element in myArray" :key="element.id" class="item">
        {{element.name}}
    </div>
    <button slot="header" @click="addPeople">Add</button>
</draggable>

Footer

Use the footer slot to add none-draggable element inside the vuedraggable component. Important: it should be used in conjunction with draggable option to tag draggable elements. Note that footer slot will always be added after the default slot regardless its position in the template. Ex:

<draggable v-model="myArray" draggable=".item">
    <div v-for="element in myArray" :key="element.id" class="item">
        {{element.name}}
    </div>
    <button slot="footer" @click="addPeople">Add</button>
</draggable>

Gotchas

  • Vue.draggable children should always map the list or value prop using a v-for directive

    • You may use header and footer slot to by-pass this limitation.
  • Children elements inside v-for should be keyed as any element in Vue.js. Be carefull to provide revelant key values in particular:

    • typically providing array index as keys won't work as key should be linked to the items content
    • cloned elements should provide updated keys, it is doable using the clone props for example

Example

Full demo example

draggable-example

For Vue.js 1.0

See here

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

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?

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.

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.

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.

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/

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?

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!

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!

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?

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?

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!

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!

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.

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

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?

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

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

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

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.

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

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!

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.

troubble in using vuex

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

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?

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'
      }]
    }
  }
});


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

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,

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

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.

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.

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.

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.