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

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

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

一、代码-验证过程

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

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

1、index.vue中的代码

<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、子组件代码

<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

 代码如下:

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

打印结果:

  • 14
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值