通过vue.draggable的chosenClass属性设置选中元素的样式,可以通过自定义样式来方便的区分出那个元素被选中。
<template>
<div>
<!--使用chosenClass属性-->
<div class="itxst">
<div>自定义控制拖拽和停靠</div>
<div class="col">
<draggable v-model="arr1" group="itxst" ghostClass="ghost" chosenClass="chosen" filter=".forbid" animation="300" :move="onMove">
<transition-group>
<div :class="item.id==1?'item forbid':'item'" v-for="item in arr1" :key="item.id">{{item.name}}</div>
</transition-group>
</draggable>
</div>
<div class="col">
<draggable v-model="arr2" group="itxst" ghostClass="ghost" chosenClass="chosen" filter=".forbid" animation="300" :move="onMove">
<transition-group>
<div :class="item.id==1?'item forbid':'item'" v-for="item in arr2" :key="item.id">{{item.name}}</div>
</transition-group>
</draggable>
</div>
</div>
</div>
</template>
例子
<template>
<div>
<!--使用draggable组件-->
<div class="itxst">
<div>自定义控制拖拽和停靠</div>
<div class="col">
<draggable v-model="arr1" group="itxst" ghostClass="ghost" chosenClass="chosen" filter=".forbid" animation="300" :move="onMove">
<transition-group>
<div :class="item.id==1?'item forbid':'item'" v-for="item in arr1" :key="item.id">{{item.name}}</div>
</transition-group>
</draggable>
</div>
<div class="col">
<draggable v-model="arr2" group="itxst" ghostClass="ghost" chosenClass="chosen" filter=".forbid" animation="300" :move="onMove">
<transition-group>
<div :class="item.id==1?'item forbid':'item'" v-for="item in arr2" :key="item.id">{{item.name}}</div>
</transition-group>
</draggable>
</div>
</div>
</div>
</template>
<script>
//导入draggable组件
import draggable from 'vuedraggable'
export default {
//注册draggable组件
components: {
draggable,
},
data() {
return {
//定义要被拖拽对象的数组
arr1:[
{ id: 1, name: 'www.itxst.com(不允许停靠)' },
{ id: 2, name: 'www.jd.com' },
{ id: 3, name: 'www.baidu.com' },
{ id: 5, name: 'www.google.com' },
{ id: 4, name: 'www.taobao.com(不允许拖拽)' }
],
arr2:[
{ id: 11, name: '微软' },
{ id: 12, name: '亚马逊' },
{ id: 13, name: '京东' },
{ id: 15, name: '谷歌' },
{ id: 14, name: '苹果' }
]
};
},
methods: {
//move回调方法
onMove(e,originalEvent){
//不允许停靠
if (e.relatedContext.element.id == 1) return false;
//不允许拖拽
if (e.draggedContext.element.id == 4) return false;
return true;
},
},
};
</script>
<style scoped>
/*定义要拖拽元素的样式*/
.drag{
background-color:blue !important;
border: solid 3px red;
}
.chosen{
background-color: #000 !important;
color: #fff;
}
.ghost{
background-color: red !important;
}
.itxst {
margin: 10px;
text-align :left;
}
.col {
width: 40%;
flex: 1;
padding: 10px;
border: solid 1px #eee;
border-radius: 5px;
float: left;
}
.col + .col {
margin-left: 10px;
}
.item {
padding: 6px 12px;
margin: 0px 10px 0px 10px;
border: solid 1px #eee;
background-color: #f1f1f1;
text-align: left;
}
.item + .item {
border-top: none;
margin-top: 6px;
}
.item:hover {
background-color: #fdfdfd;
cursor: move;
}
</style>