Id | Name |
---|---|
1 | Joao |
2 | Jean |
3 | Johanna |
4 | Juan |
[ { "name": "Joao", "id": "1" }, { "name": "Jean", "id": "2" }, { "name": "Johanna", "id": "3" }, { "name": "Juan", "id": "4" } ]
使用组件操作目标容器它会以VueDraggable为根元素往下查找最近的.el-table选择器
由于我们平时使用的过程中,很多需要拖拽的组件并非我们的直系子元素,所以我们需要指定一个目标容器,来完成拖拽的功能,我们可以通过 target
属性来指定目标容器。
此处我们以第三方组件为例,假设el-table
为第三方组件
WARNING
注意:只要您能确保获取到的目标元素是正确的,都可以完成我们的功能,如果您在使用过程中发现目标元素未找到,请检查您所输入的选择器是否正确
ElTable.vue
<template>
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody class="el-table">
<tr v-for="item in list" :key="item.name" class="cursor-move">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
</tr>
</tbody>
</table>
</template>
<script setup lang="ts">
interface Props {
list: Record<'name' | 'id', string>[]
}
defineProps<Props>()
</script>
Id | Name |
---|---|
1 | Joao |
2 | Jean |
3 | Johanna |
4 | Juan |
[ { "name": "Joao", "id": "1" }, { "name": "Jean", "id": "2" }, { "name": "Johanna", "id": "3" }, { "name": "Juan", "id": "4" } ]
<template>
<section>
<div>
<VueDraggable v-model="list" :animation="150" target=".el-table">
<ElTable :list="list"></ElTable>
</VueDraggable>
</div>
<div class="flex justify-between">
<preview-list :list="list" />
</div>
</section>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { VueDraggable } from 'vue-draggable-plus'
import ElTable from './ElTable.vue'
const list = ref([
{
name: 'Joao',
id: '1'
},
{
name: 'Jean',
id: '2'
},
{
name: 'Johanna',
id: '3'
},
{
name: 'Juan',
id: '4'
}
])
</script>
Id | Name |
---|---|
1 | Joao |
2 | Jean |
3 | Johanna |
4 | Juan |
[ { "name": "Joao", "id": "1" }, { "name": "Jean", "id": "2" }, { "name": "Johanna", "id": "3" }, { "name": "Juan", "id": "4" } ]
<template>
<div>
<div id="my-container">
<ElTable :list="list"></ElTable>
</div>
<div class="flex justify-between">
<preview-list :list="list" />
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, getCurrentInstance } from 'vue'
import { useDraggable } from 'vue-draggable-plus'
import ElTable from './ElTable.vue'
const vm = getCurrentInstance()
onMounted(() => {
console.log(vm)
})
const list = ref([
{
name: 'Joao',
id: '1'
},
{
name: 'Jean',
id: '2'
},
{
name: 'Johanna',
id: '3'
},
{
name: 'Juan',
id: '4'
}
])
useDraggable('#my-container .el-table', list)
</script>
使用 function
时请保证组件内只有一个根元素
这种用法是错误的,因为它包含多个根元素
<template>
<!-- ❌ -->
<div id="my-container">
<ElTable :list="list"></ElTable>
</div>
<div class="flex justify-between">
<pre class="code-block">{{ text }}</pre>
</div>
</template>
这种方式是正确的,因为它只有一个根元素
<template>
<!-- ✅ -->
<div>
<div id="my-container">
<ElTable :list="list"></ElTable>
</div>
<div class="flex justify-between">
<pre class="code-block">{{ text }}</pre>
</div>
</div>
</template>