为什么在Vue中 '@drop' 事件不起作用?

26

@drop监听器对我不起作用。它没有调用我要求它调用的方法。

我想拖动芯片并能在另一个组件上将其放下并执行功能,但在放下芯片时,dropLink方法没有被执行,因此我认为@drop事件没有被触发。

控制台上没有显示任何错误。

其余事件都正常工作,如@dragstart

这是我使用的组件的代码:

<template>
  <div
    @keydown="preventKey"
    @drop="dropLink"
  >
    <template
      v-if="!article.isIndex"
    >
      <v-tooltip bottom>
        <template v-slot:activator="{ on }">
          <v-chip
            small
            draggable
            class="float-left mt-2"
            v-on="on"
            @dragstart="dragChipToLinkToAnotherElement"
          >
            <v-icon x-small>
              mdi-vector-link
            </v-icon>
          </v-chip>
        </template>
        <span>Link</span>
      </v-tooltip>

      <v-chip-group
        class="mb-n2"
        show-arrows
      >
        <v-chip
          v-for="(lk, index) in links"
          :key="index"
          small
          outlined
          :class="{'ml-auto': index === 0}"
        >
          {{ lk.text }}
        </v-chip>
      </v-chip-group>
    </template>

    <div
      :id="article.id"
      spellcheck="false"
      @mouseup="mouseUp($event, article)"
      v-html="article.con"
    />
  </div>
</template>

<script>
export default {
  name: 'ItemArticle',
  props: {
    article: {
      type: Object,
      required: true
    }
  },
  computed: {
    links () {
      return this.article.links
    }
  },
  methods: {
    mouseUp (event, article) {
      this.$emit('mouseUp', { event, article })
    },
    preventKey (keydown) {
      this.$emit('preventKey', keydown)
    },
    dragChipToLinkToAnotherElement (event) {
      event.dataTransfer.setData('text/plain', this.article.id)
    },
    dropLink (e) {
      //but this method is never called
      console.log('evento drop is ok', e)
    }
  }
}
</script>

在这个项目中,我也使用了Nuxt,如果相关的话。

1个回答

55
为了使div成为一个可放置的目标,需要取消divdragenterdragover事件。Firefox还需要取消drop事件
您可以使用.prevent事件修饰符在这些事件上调用Event.preventDefault()
<div @drop.prevent="dropLink" @dragenter.prevent @dragover.prevent></div>

如果您需要根据拖动数据类型接受/拒绝拖放,请设置一个处理程序,有条件地调用Event.preventDefault()

<div @drop.prevent="dropLink" @dragenter="checkDrop" @dragover="checkDrop"></div>

export default {
  methods: {
    checkDrop(e) {
      if (/* allowed data type */) {
        e.preventDefault()
      }
    },
  }
}

演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接