前の記事の、
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要素を参照しています。
const handleRef = useTemplateRef('handle');
const {
x: xd,
y: yd,
style: styled,
} = useDraggable(draggable, {
initialValue: { x: 40, y: 40 },
handle: handleRef
});
stackblitz で書いた。
前記事では、赤い部分全体、どこをマウスカーソルでドラッグしても、ドラッグ可能でしたが、
今回は、背景が黄色の部分のみ、ドラッグできます。赤の部分をカーソルで触っても、ドラッグできません。
コード
以下、stackblitzの、HelloWorld.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 埋め込み。
本記事の、サンプル
前の記事のサンプルは、下記

