知海

指定目标容器

vue-draggable-plus指南-教程

map:
path: /demo/target-container

指定目标容器

由于我们平时使用的过程中,很多需要拖拽的组件并非我们的直系子元素,所以我们需要指定一个目标容器,来完成拖拽的功能,我们可以通过 target 属性来指定目标容器。

此处我们以第三方组件为例,假设el-table为第三方组件

⚠️ 警告
注意:只要您能确保获取到的目标元素是正确的,都可以完成我们的功能,如果您在使用过程中发现目标元素未找到,请检查您所输入的选择器是否正确

ElTable.vue

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>

组件使用

vue 复制代码
<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>

函数使用

vue 复制代码
<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 时请保证组件内只有一个根元素

错误使用

这种用法是错误的,因为它包含多个根元素

vue 复制代码
<template>
  <!-- ❌ -->
  <div id="my-container">
    <ElTable :list="list"></ElTable>
  </div>
  <div class="flex justify-between">
    <pre class="code-block">{{ text }}</pre>
  </div>
</template>

正确使用

这种方式是正确的,因为它只有一个根元素

vue 复制代码
<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>

帮助我们改进文档

发现翻译问题或内容错误?请告诉我们。