vuedraggable把方块从上面拉到div里面示例代码
时间: 2023-07-04 19:18:27 浏览: 171
好的,这里是一个完整的示例代码,可以帮助您更好地理解如何使用vuedraggable将方块从上面拉到div中:
```html
<template>
<div>
<div class="draggable-item" v-for="item in items" :key="item.id" v-model="items" :class="{ 'drag-handle': true }">
{{ item.name }}
</div>
<div class="dropzone" v-dropzone>
Drop here
</div>
</div>
</template>
<script>
import draggable from 'vuedraggable';
export default {
components: {
draggable,
},
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
],
};
},
directives: {
dropzone: {
bind(el, binding) {
el.addEventListener('dragover', (e) => {
e.preventDefault();
el.classList.add('dragover');
});
el.addEventListener('dragleave', (e) => {
el.classList.remove('dragover');
});
el.addEventListener('drop', (e) => {
e.preventDefault();
el.classList.remove('dragover');
const data = JSON.parse(e.dataTransfer.getData('text/plain'));
binding.value(data);
});
},
},
},
methods: {
handleDrop(item) {
const index = this.items.indexOf(item);
this.items.splice(index, 1);
},
},
};
</script>
<style>
.draggable-item {
cursor: move;
}
.drag-handle {
background-color: #f0f0f0;
border: 1px solid #ddd;
padding: 10px;
margin: 10px 0;
}
.dropzone {
height: 200px;
border: 1px dashed #ddd;
display: flex;
justify-content: center;
align-items: center;
}
.dragover {
background-color: #f0f0f0;
}
</style>
```
在这个示例中,我们使用了v-dropzone自定义指令来实现将方块拖到div中的逻辑。在组件中,我们为draggable-item元素添加了一个drag-handle类,以便指定可拖动的元素。我们还为dropzone元素添加了一个v-dropzone指令,以便指定拖放目标区域。在方法中,我们使用handleDrop方法来处理拖放操作的逻辑。
阅读全文