在vue.draggable.next拖拽差中使用组件时遇到的问题

vue.draggable.next 中文文档 - itxst.com

问题描述在draggable标签中定义的组件,通过ref不能正确拿到相应数组

一、代码-验证过程

vue3中定义组件的ref,如果有多个相同名称的组件,会将ref.value的值变为数组

在vue.draggable.next提供的draggable标签中定义组件,如果有多个相同名称的组件,ref.value的值为循环后的最后一个数据

1、index.vue中的代码

html 复制代码
<template>
  <div class="">
    <draggable
      :list="perList"
      ghost-class="ghost"
      chosen-class="chosenClass"
      animation="300"
      @start="onStart"
      @end="onEnd"
    >
      <template #item="{ element,index }">
        <div class="item">
          <TestChild :index="index" :info="element" ref="dragRef"/>
        </div>
      </template>
    </draggable>
    <hr>
    <div v-for="i in 3" class="item">
      <TestChild :index="i" :info="perList[i]" ref="vforChild"/>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import draggable from "vuedraggable";
import TestChild from "./children/00-test.vue";

let dragRef = ref([])
let vforChild = ref([])
const perList = reactive([
  {name:'薛薛',age:18},
  {name:'婷婷',age:18},
  {name:'大大',age:1},
  {name:'小小',age:1},
])
function onStart(){
  console.log(dragRef,'dragRef')
  console.log(vforChild,'vforChild')
}
function onEnd(){
  console.log('拖拽结束');
}
</script>
<style lang="scss" scoped>
.item{
  width: 200px;
  border: 1px solid #333;
  margin: 3px auto;
}
</style>

2、子组件代码

html 复制代码
<template>
  <div class="">
    {{ index }} - {{ info.name }}
  </div>
</template>

<script setup lang="ts">
let props = defineProps(["index","info"])
defineExpose({name:props.info.name})
</script>
<style lang="scss" scoped>

</style>

3、页面打印结果

二、解决方式:使用回调函数形式定义组件的ref

代码如下:

html 复制代码
<draggable
  :list="perList"
  ghost-class="ghost"
  chosen-class="chosenClass"
  animation="300"
  @start="onStart"
  @end="onEnd"
>
  <template #item="{ element,index }">
    <div class="item">
      <TestChild :index="index" :info="element" :ref="r=>dragRef[index] = r"/>
    </div>
  </template>
</draggable>

//let dragRef = ref([])

打印结果:

相关推荐
naice11 小时前
我对github的图片很不爽了,于是用AI写了一个图片预览插件
前端·javascript·git
天蓝色的鱼鱼11 小时前
Element UI 2.X 主题定制完整指南:解决官方工具失效的实战方案
前端·vue.js
RoyLin12 小时前
TypeScript设计模式:门面模式
前端·后端·typescript
小奋斗12 小时前
千量数据级别的数据统计分析渲染
前端·javascript
小文刀69612 小时前
CSS-响应式布局
前端
三小河12 小时前
overflow:auto 滚动的问题,以及flex 布局中如何设置
前端·javascript
薛定谔的算法12 小时前
phoneGPT:构建专业领域的检索增强型智能问答系统
前端·数据库·后端
Hilaku12 小时前
Token已过期,我是如何实现无感刷新Token的?
前端·javascript·面试
小文刀69612 小时前
2025-35st-w-日常开发总结
前端
我是日安12 小时前
从零到一打造 Vue3 响应式系统 Day 8 - Effect:深入剖析嵌套 effect
前端·vue.js