axis

axis

Restrict movement to a single axis (x or y)

The axis plugin locks movement to horizontal (x) or vertical (y) direction. Perfect for sliders, scrollbars, or any UI requiring one-dimensional dragging.

axis('x'); // Only horizontal movement
axis('y'); // Only vertical movement
axis(null); // Free movement (removes constraint)

Basic Usage

<script setup>
import { axis, vDraggable } from '@neodrag/vue';
</script>

<template>
  <div>
    <div v-draggable="[axis('x')]">Horizontal only</div>
    <div v-draggable="[axis('y')]">Vertical only</div>
    <div v-draggable="[axis(null)]">Any direction</div>
  </div>
</template>

Dynamic Axis Switching

<script setup>
import { ref } from 'vue';
import { axis, vDraggable, useCompartment } from '@neodrag/vue';

const currentAxis = ref('x');
const axisComp = useCompartment(() => axis(currentAxis.value));

function switchAxis() {
  currentAxis.value = currentAxis.value === 'x' ? 'y' : 'x';
}
</script>

<template>
  <div>
    <div v-draggable="() => [axisComp]">
      Currently locked to: {{ currentAxis }} axis
    </div>
    <button @click="switchAxis">
      Switch to {{ currentAxis === 'x' ? 'Y' : 'X' }} axis
    </button>
  </div>
</template>

Real-World Examples

Horizontal Slider Component

<script setup>
import { ref } from 'vue';
import {
  axis,
  bounds,
  BoundsFrom,
  events,
  vDraggable,
} from '@neodrag/vue';

const track = ref();
const value = ref(50);

function handleDrag(data) {
  if (track.value) {
    const trackWidth = track.value.offsetWidth;
    value.value = Math.round((data.offset.x / trackWidth) * 100);
  }
}

const plugins = [
  axis('x'),
  bounds(() => BoundsFrom.element(track.value)),
  events({ onDrag: handleDrag }),
];
</script>

<template>
  <div>
    <div ref="track" class="track">
      <div v-draggable="plugins" class="handle" />
    </div>
    <p>Value: {{ value }}%</p>
  </div>
</template>

Split Pane Resizer

// Vertical divider for horizontal split
const plugins = [
  axis('x'),
  bounds(
    BoundsFrom.parent({
      left: 100, // Min pane width
      right: 100, // Min pane width
    }),
  ),
];

How It Works

The axis plugin modifies the proposed movement during dragging:

  • axis('x'): Sets proposed.y = null (no vertical movement)
  • axis('y'): Sets proposed.x = null (no horizontal movement)
  • axis(null): No changes (free movement)

This happens in the plugin’s drag hook, so other plugins receive the constrained movement values.

API Reference

function axis(value?: 'x' | 'y' | null | undefined): Plugin;

Parameters:

  • value - The axis to constrain movement to
    • 'x' - Horizontal only
    • 'y' - Vertical only
    • null or undefined - No constraint

Returns: A plugin object for use with draggable.