Vue Dragula-多次调用下降事件侦听器

时间:2020-01-18 15:45:51

标签: javascript vue.js vuejs2 dragula

我正在尝试使用Vue.js和vue-dragula框架构建具有可拖动元素的Web应用程序。在该应用中,我尝试使用多个容器,这些容器中的元素可以在容器中拖动。

在App.vue中

<template>
   <div v-for="container in containers">
      <container/>
   </div>
</template>

在Container.vue中

<template>
   <div v-dragula="elements" bag="first-bag">
      <div v-for="element in elements" :key="element.id">
         <element v-bind="element"/>
      </div>
   </div>
</template>
export default {
   mounted() {
      Vue.$dragula.$service.eventBus.$on('drop', () => {
         console.log('Dropped');
      });
   }
}

我正在尝试启用事件侦听器,该侦听器能够检测何时删除了元素。当前事件侦听器方法有效时,将多次调用它。具体来说,它称为容器数组的长度。例如,如果容器是长度为6的数组,则将“ Dropped”记录6次。我如何拥有它,以便drop的事件侦听器仅被调用一次?

1 个答案:

答案 0 :(得分:0)

我在下面的解决方法。

App.vue

<template>
   <div v-for="(container, containerIndex) in containers">
      <container :containerIndex="containerIndex" />
   </div>
</template>

在Container.vue中

<template>
   <div v-dragula="elements" :bag="'first-bag-'+containerIndex">
      <div v-for="element in elements" :key="element.id">
         <element v-bind="element"/>
      </div>
   </div>
</template>
<script>
   export default {
      props: ['containerIndex'],
      mounted() {
         Vue.$dragula.$service.eventBus.$on('drop', ([bag, curElmt, allElmts]) => {
            if (bag == 'first-bag-'+this.containerIndex) {
               console.log('Dropped'); // This line is not repate based on containers length
            }
         });
      }
   }
<script>