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

打印结果:

相关推荐
前端市界1 分钟前
实用指南:如何本地化部署 Sentry (Self-Hosted) 完整教程
前端
颂love3 分钟前
TypeScript速学
前端·javascript·typescript
IT策士9 分钟前
第 46 篇 k8s之CI/CD 集成:GitOps 理念与 ArgoCD
前端·容器·kubernetes
Dalydai12 分钟前
AI 辅助大屏开发:怎么让 AI 干活,但别让它干砸
前端
凌涘12 分钟前
深入理解 JavaScript 执行机制:从执行上下文到调用栈全解析
前端·javascript
utmhikari12 分钟前
【AI原生】用Vibe Coding写产品前端原型的一些经验
前端·ai·产品经理·web·web开发·ai-native·qoder
li星野13 分钟前
从零搭建文件上传系统:FastAPI 后端 + Streamlit 前端
前端·状态模式·fastapi
YAwu1116 分钟前
手写一个符合 Promise/A+ 规范的 Promise(附完整代码)
前端·javascript
暗不需求17 分钟前
从路虎汽车小程序看微信小程序开发的最佳实践
前端·javascript·微信小程序
用户0595401744618 分钟前
我把RAG对话记忆测试从手工用例改成ChromaDB自动化评估,Bug发现率翻了4倍
前端·css