0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

VueUse ドラッグする。(2)

Posted at

前の記事の、
VueUseの、useDraggable を使ってドラッグ&ドロップの続きで、

「マウスで掴む場所を指定できる」

これをやってみます。

公式ページのUsageの方には、例として載っていないです。
https://vueuse.org/core/useDraggable/#usage

公式ページDemoのソースを見ると、コンポーネントVersionでのやり方は載っていますが。
https://github.com/vueuse/vueuse/blob/main/packages/core/useDraggable/demo.vue

This function also provides a renderless component version via the @vueuse/components package. Learn more about the usage.

今回は、コンポーネントVersionではなく、普通のやり方でやります。

マウスで掴む場所を指定するためには、handleオプションを使います。

まず、テンプレートに、ドラッグする部分(divで囲った)を追加して、ref="handle"としておきます。

テンプレート
  <div
    ref="draggable"
    :style="{
      userSelect: 'none',
      position: 'fixed',
      width: '250px',
      height: '250px',
      background: 'red',
      top: `${yd}px`,
      left: `${xd}px`,
    }"
  >
    x: {{ xd }}, y: {{ yd }}

    <div ref="handle" class="handle">
      <p>ここをドラッグする</p>
    </div>
  </div>

js側では、
useDraggable の、handleオプションに、handleRef を指定しています。
handleRef は、useTemplateRefを使って、テンプレート中の、ref="handle"としたDiv要素を参照しています。

javascript
const handleRef = useTemplateRef('handle');

const {
  x: xd,
  y: yd,
  style: styled,
} = useDraggable(draggable, {
  initialValue: { x: 40, y: 40 },
  handle: handleRef
});

stackblitz で書いた。

前記事では、赤い部分全体、どこをマウスカーソルでドラッグしても、ドラッグ可能でしたが、

スクリーンショット 2025-09-24 231147.png

今回は、背景が黄色の部分のみ、ドラッグできます。赤の部分をカーソルで触っても、ドラッグできません。

スクリーンショット 2025-10-20 165225.png

コード

以下、stackblitzの、HelloWorld.vueのコード

vue
<script setup>
import { useTemplateRef } from 'vue';
import { useMouse, useDraggable, useElementBounding } from '@vueuse/core';

const { x, y } = useMouse();

const draggable = useTemplateRef('draggable');
const handleRef = useTemplateRef('handle');

const {
  x: xd,
  y: yd,
  style: styled,
} = useDraggable(draggable, {
  initialValue: { x: 40, y: 40 },
  handle: handleRef,
});
</script>

<template>
  <div>マウス座標:{{ x }}, {{ y }}</div>

  <div
    ref="draggable"
    :style="{
      userSelect: 'none',
      position: 'fixed',
      width: '250px',
      height: '250px',
      background: 'red',
      top: `${yd}px`,
      left: `${xd}px`,
    }"
  >
    x: {{ xd }}, y: {{ yd }}

    <div ref="handle" class="handle">
      <p>ここをドラッグする</p>
    </div>
  </div>
</template>

<style scoped>
.handle {
  color: red;
  background-color: yellow;
  margin: 60px;
}
</style>

stackblitz 埋め込み。

本記事の、サンプル

前の記事のサンプルは、下記

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?