A simplest way to integrate drag on Vue.js
v-drag
Draggable elements are a common UX pattern, specially on touch screens. But as a developer, you might know how challenging it is to apply it with JavaScript. Vue.js doesn’t help in this case, either. So to simplify things, v-drag was written. Its aim is to quickly integrate and customize draggable elements on projects using Vue.js.
Installation
npm install v-drag --save
v-drag’s source code is also available uncompressed and minified.
Usage
Import v-drag into any file you are planning to use it. You can use either import or require, although the first one is recommended as it’s part of the ES6 spec:
import drag from "v-drag"
const drag = require("v-drag");
Then call the v-drag plugin:
Vue.use(drag);
No extra setup is necessary at this point. Add the v-drag
attribute to any element to make it draggable:
<div v-drag>Drag me!</div>
Options
The default behavior for any element with the v-drag
attribute is to be draggable in any direction and without a handle. However, this can be changed using an object or its equivalent shortcuts:
<div v-drag="{ axis: 'x', handle: '#someElement' }">
<div id="someElement">Handle</div>
</div>
Both the object and the values can be declared inline, as in the example above, or using the data
object, computed properties, methods, props,…
Axis
Constrains the element to move only in one direction: horizontal or vertical.
Values
x
: horizontal movementy
: vertical movement
Shortcut
<div v-drag:x>Horizontal</div>
Handle
Informs that the element can only be dragged using another element, known as handle. It’s not necessary for the handle to be located inside the draggable element, and each element can have more than one handle.
Values
Handle’s name must be a selector, the same used to refer to the element in CSS.
Note: previously, handles were only declared with IDs, updating to v-drag v2.1.0
or higher will mean you will also have to update the handle declarations, if you use them.
Shortcut
<div v-drag="'.someElement'">Don’t drag me</div>
<div class="someElement">Drag me</div>
Event classes
v-drag uses CSS classes to add basic styling to the draggable elements. You can override one or multiple of the default classes when the plugin is called:
Vue.use(drag, {
eventClass: {
down: "is-pressed",
move: "is-moving"
}
});
This are the default classes with its values:
Name | Default value | Description |
---|---|---|
initial |
drag-draggable |
The element is draggable |
hasHandle |
drag-uses-handle |
The element uses a handle |
handle |
drag-handle |
The element is the handle of another element |
down |
drag-down |
The user has pressed the element |
move |
drag-move |
The user has started to drag the element |