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

打印结果:

相关推荐
嘟嘟071722 分钟前
React 受控组件与非受控组件:表单数据到底归谁管?
前端·javascript·react.js
嘟嘟071723 分钟前
React 表单管理进阶:从单字段到带校验的完整登录表单
前端·javascript·react.js
光影少年31 分钟前
react navite原生事件监听、全局事件通知
前端·react native·react.js
lvv33 分钟前
不会被渲染的组件,为什么让我的首屏白屏了?(一次前端问题总结)
前端·webpack·性能优化
码上成长1 小时前
微前端 Invalid hook call?先把「window 注入 + externals」整明白
前端·react.js·前端框架
宿6741 小时前
vue3-DOM树
前端·javascript·vue.js
白狐_7982 小时前
408数据结构:中缀转后缀与操作符栈容量——真题精讲
前端·javascript·数据结构
谷哥的小弟2 小时前
TypeScript在Vue3中的常见写法
前端·javascript·typescript
人间凡尔赛2 小时前
2026 前端全栈新范式:Server Actions + Edge Runtime,告别传统 API 路由
前端·全栈·next.js
码林鼠5 小时前
2026前端面试题(二)
前端