vue2.0使用Sortable.js实现的拖拽功能

简介

在使用vue1.x之前的版本的时候,页面中的拖拽功能,我在项目中是直接用的jQuery ui中的sortable.js,只是在拖拽完成后,在update的回调函数中又重新排序了存放数据的数组。但是当把vue升级到2.0以上后发现拖拽功能失效了,于是使用了下面代码。

该案例主要是在用于vuejs2.0中实现的拖拽功能,用到的的js有Sortable.js,vuedraggable.js,当然还有vue.min.js,提供的案例使用的require.js加载.

html主要代码

1 <draggable :list="list2" :move="getdata" @update="datadragEnd" :options="{animation: 300,handle:'.dargDiv'}">
2         <transition-group name="list-complete" >
3             <div v-for="element in list2" :key="element.it.name"  class="list-complete-item">
4                 <div class="styleclass dargDiv">{{element.id}}</div>
5                 <div class="styleclass">{{element.it.name}}</div>
6 
7             </div>
8         </transition-group>
9    </draggable>

css代码

 1 body{
 2     font-family:'微软雅黑'
 3 }
 4 [v-cloak]{
 5     display:none;
 6 }
 7 #example{
 8     1000px;
 9     margin:0 auto;
10 }
11 .list-complete-item {
12   transition: all 1s;
13     height:50px;
14     line-height: 50px;
15     background: #000;
16     color:#fff;
17     text-align: center;
18     font-size:24px;
19     margin-top:10px;
20 }
21 .styleclass{
22     100px;
23     float:left;
24 }
25 .list-complete-enter, .list-complete-leave-active {
26   opacity: 0;
27   height: 0px;
28   margin-top: 0px;
29   padding: 0px;
30   border: solid 0px;
31 }
32 .list-complete-sortable-chosen,.list-complete-sortable-ghost{
33  opacity: 0;
34   height: 0px;
35   margin-top: 0px;
36   padding: 0px;
37   border: solid 0px;
38 }
39 .dargDiv{
40     cursor:move;
41     background:red;
42 }
43 .wrods{
44     margin-top:50px;
45 }
46 p{
47     line-height:24px;
48     text-align:center;
49 }

js代码

 1 require(['vue','vuedraggable'],function(Vue,draggable){
 2     Vue.component('draggable', draggable);
 3      new Vue({
 4         el: '#example',
 5         data: {
 6            list2:[
 7            {id:"id1",it:{name:'bbbb'}},
 8            {id:"id2",it:{name:'2222'}},
 9            {id:"id3",it:{name:'3333'}},
10            {id:"id4",it:{name:'4444'}}
11            ]
12         },
13         methods:{
14             getdata: function(evt){
15                 console.log(evt.draggedContext.element.id);
16             },
17             datadragEnd:function(evt){
18                 console.log('拖动前的索引:'+evt.oldIndex);
19                 console.log('拖动后的索引:'+evt.newIndex);
20 
21             }
22 
23         }
24     })
25 
26 })

里面的可配置的很多细节请参考参考地址,这里不做详细介绍.

可下载案例地址:https://github.com/hxlmqtily1314/Vue.Draggable-case
参考地址:https://github.com/SortableJS/Vue.Draggable

原文地址:https://www.cnblogs.com/yuwenjing0727/p/7146822.html