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

打印结果:

相关推荐
普通人610 分钟前
CSS-box-sizing-使用指南
开发语言·前端·css·1024程序员节
风骏时光牛马15 分钟前
AI开源工具一站式尝鲜体验
前端
IT_陈寒23 分钟前
Python项目实战经验分享:为什么你的多进程日志会丢失?
前端·人工智能·后端
柳杉31 分钟前
让 AI 学会审美、建模和剪片:我收藏夹里的 14 个仓库
前端·ai编程·three.js
前端架构师-老李36 分钟前
HTML与CSS基础第七课—HTML 中的a标签(跳转链接)
前端·css·html
陈随易1 小时前
一个网吧网管,做了个网页,卖了 5000 万
前端·后端·程序员
jktantan9 小时前
Vue keep-alive 切标签后滚动位置回顶?因为 onDeactivated 里读到的 scrollTop 是 0
前端·javascript·vue.js
2601_9628857210 小时前
quotes 字段全解:涨跌幅、振幅、换手率的口径与单位
java·前端·spring
excel11 小时前
encodeURI 和 encodeURIComponent 有什么区别?
前端
前端精髓11 小时前
调用openrouter的免费API模型
java·前端·javascript