在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([])

打印结果:

相关推荐
GISer_Jing5 分钟前
TypeScript打造高效MCP工具与Skills开发
前端·javascript·typescript
智能工业品检测-奇妙智能10 分钟前
如何用OpenClaw实现CSDN文章编辑发布
前端·人工智能·chrome·奇妙智能
Cache技术分享10 分钟前
351. Java IO API - Java 文件操作:java.io.File 与 java.nio.file 功能对比 - 3
前端·后端
A_nanda26 分钟前
vue实现走马灯显示文字效果
前端·javascript·vue.js
小码哥_常28 分钟前
Kotlin 延迟初始化:lateinit与by lazy的华山论剑
前端
晴栀ay36 分钟前
一文详解JS中的执行顺序——事件循环(宏任务、微任务)
前端·javascript·面试
张元清1 小时前
React 19 Hooks:新特性及高效使用指南
前端·javascript·面试
敏捷建模1 小时前
Zig语言能够编写同时针对PC端和手机端自适应的软件吗
前端
Hello_Embed1 小时前
LVGL 入门(四):大小坐标与盒子模型
前端·笔记·stm32·单片机·嵌入式