vue拖拽已有的属性到不同的框内示例代码
时间: 2024-02-19 14:03:43 浏览: 10
好的,这里是一个示例代码,演示如何实现将已有属性拖拽到不同的框内:
```html
<template>
<div class="container">
<div class="attribute-list">
<div class="attribute-item" v-for="(attribute, index) in attributes" :key="attribute.id" :draggable="true" @dragstart="startDragging(attribute)">
{{ attribute.name }}
</div>
</div>
<div class="box" v-for="(box, index) in boxes" :key="box.id" :class="'box-' + (index + 1)" @dragover.prevent @drop="handleDrop(box)">
<div class="box-header">
Box {{ index + 1 }}
</div>
<div class="box-attributes">
<div class="attribute-item" v-for="(attribute, i) in box.attributes" :key="attribute.id">
{{ attribute.name }}
<span class="drag-handle" v-if="i !== 0" @mousedown="startDragging(box, i)">☰</span>
<button @click="removeAttribute(box, i)">删除</button>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
attributes: [
{ id: 1, name: '颜色' },
{ id: 2, name: '尺码' },
{ id: 3, name: '重量' },
{ id: 4, name: '材质' },
],
boxes: [
{
id: 1,
attributes: [
{ id: 1, name: '颜色' },
{ id: 2, name: '尺码' },
],
},
{
id: 2,
attributes: [
{ id: 3, name: '重量' },
{ id: 4, name: '材质' },
],
},
],
dragging: null,
};
},
methods: {
startDragging(attribute) {
this.dragging = attribute;
},
removeAttribute(box, index) {
box.attributes.splice(index, 1);
},
handleDrop(box) {
if (this.dragging) {
const attribute = this.dragging;
const existingAttribute = box.attributes.find((a) => a.id === attribute.id);
if (!existingAttribute) {
box.attributes.push(attribute);
}
}
this.dragging = null;
},
},
};
</script>
<style>
.container {
display: flex;
}
.attribute-list {
width: 200px;
}
.attribute-item {
cursor: move;
padding: 5px;
margin-bottom: 5px;
border: 1px solid #ddd;
}
.box {
width: 200px;
margin-left: 20px;
border: 1px solid #ddd;
}
.box-header {
background-color: #f0f0f0;
padding: 10px;
}
.box-attributes {
padding: 10px;
}
.drag-handle {
cursor: move;
margin-right: 10px;
}
</style>
```
在这个示例中,我们首先定义了一个包含属性列表和框的容器。属性列表中包含所有可拖动的属性元素。框中包含已经被拖动到该框内的属性元素。我们为属性元素设置了可拖动属性,并使用@dragstart事件来设置dragging变量。我们还为每个框元素添加了@dragover.prevent和@drop事件,以便在放置属性时处理拖放操作。在方法中,我们使用startDragging方法来设置dragging变量,使用removeAttribute方法来删除属性,使用handleDrop方法来处理拖放操作的逻辑。我们还使用了CSS来美化页面。