首页 > 解决方案 > How to programmatically trigger a draggable "move" event by a click in Vue?

问题描述

I have a set of cards that are arranged vertically and are currently draggable. When you drag a card over another, you see this card as a semi-transparent card hovering over the target position, before you let go, the cards underneath swap positions.

I want to know how to trigger that behavior(swap positions/show animation of moving up/down) without dragging eg. click arrows up/down.

To clarify: "trigger event" as in not call the method that responds to the moving event(ending) but make the cards move as if a mouse/finger dragged the cards in a direction(up/down).

For now I have added a position switch that reorders the array but it does not trigger the visual aspect eg. dragging. You just see a flash and then cards are ordered differently.

See visual behavior

before move

during move

after move

Draggable component

<draggable v-model="things" :move="checkPosition" :options={animation:500}">
  <div v-for="(thing, index) in things">
    <div class="up" @clickSort"('up', index)">
    <div class="down" @clickSort"('up', index)">
  </div>
</draggable>

Relevant JS methods

watch: {
  things: {
    // this fires when you sort by dragging, as well as button click
    // loop over things
    // update vuex
  }
}

checkPosition(event) {
  if (event.related) {
    // code that keeps draggable item pos in scope of existing elements
    // some are hidden
    return !event.related.classList.contains('locked');
  }
}

clickDrag(direction, itemPos) {
  // manual array sorting, no draggable event eg. hover/motion/transition
}

标签: vue.jsdraggablevuedraggable

解决方案


为了创建这个过渡效果,你必须使用 Vue 提供的 Enter/Leave Transition https://vuejs.org/v2/guide/transitions.html

当您想要触发动画时,您需要定义 Vue 将应用于您的组件的 css 动画样式,例如 ondrop 事件。


推荐阅读