nested-draggable使用
时间: 2023-08-07 18:03:43 浏览: 252
`nested-draggable` 是 `vuedraggable` 库提供的一个嵌套拖拽组件,可以用于实现多层级嵌套的拖拽排序功能。
使用 `nested-draggable`,需要先安装 `vuedraggable` 库:
```
npm install vuedraggable --save
```
然后在需要使用 `nested-draggable` 的组件中,引入 `vuedraggable` 和 `nested-draggable` 组件:
```vue
<template>
<div>
<nested-draggable v-model="list" :options="draggableOptions" class="list">
<template #default="{ element }">
<div :class="[element.type === 'folder' ? 'folder' : 'item']">
<div class="drag-handle"></div>
<div class="content">
<div>{{ element.name }}</div>
<div v-if="element.children">
<nested-draggable :list="element.children" :options="draggableOptions" class="sublist"></nested-draggable>
</div>
</div>
</div>
</template>
</nested-draggable>
</div>
</template>
<script>
import draggable from 'vuedraggable'
import nestedDraggable from 'vuedraggable/dist/vuedraggable.nested'
export default {
components: {
draggable,
nestedDraggable
},
data () {
return {
list: [
{
type: 'folder',
name: 'Folder 1',
children: [
{
type: 'item',
name: 'Item 1'
},
{
type: 'item',
name: 'Item 2'
}
]
},
{
type: 'folder',
name: 'Folder 2',
children: [
{
type: 'item',
name: 'Item 3'
}
]
}
],
draggableOptions: {
group: 'items',
animation: 150,
handle: '.drag-handle',
ghostClass: 'ghost',
chosenClass: 'chosen'
}
}
}
}
</script>
<style>
.list {
display: flex;
flex-direction: column;
padding-left: 20px;
}
.item {
display: flex;
align-items: center;
padding: 10px;
border: 1px solid #ccc;
}
.folder {
border: 1px solid #ccc;
margin-bottom: 10px;
padding: 10px;
}
.drag-handle {
width: 20px;
height: 20px;
margin-right: 10px;
background-color: #ccc;
cursor: move;
}
.chosen {
outline: 2px dashed #ccc;
}
</style>
```
在以上代码中,我们采用了 `nested-draggable` 组件实现了多层级嵌套的拖拽排序功能。在 `nested-draggable` 组件中,我们绑定了 `list` 数组作为拖拽列表,设置了拖拽配置项 `draggableOptions`,并通过插槽自定义了拖拽元素的展示方式。
需要注意的是,`nested-draggable` 中嵌套的 `nested-draggable` 组件需要绑定子列表的数据,并设置对应的拖拽配置项。在样式方面,我们通过 CSS 对拖拽元素和容器进行了样式的设置。
阅读全文