#How do I make a draggable modal in Nuxt?
3 messages · Page 1 of 1 (latest)
To create a draggable modal in Nuxt, you can combine the Modal component from Nuxt UI with a mouse-following functionality. Here's how you can approach this:
- First, use the Modal component from Nuxt UI as a base for your modal:
Modal (https://ui.nuxt.com/components/modal)
- To make the modal draggable, you can use the
useMousecomposable from VueUse, which is integrated with Nuxt:
Stack Overflow: How to make target ref move with the mouse inside a composable in Vue 3 (https://stackoverflow.com/questions/77490326)
Here's a basic example of how you could implement this:
<template>
<UModal v-model="isOpen">
<div
ref="modalContent"
:style="{ position: 'absolute', top: y + 'px', left: x + 'px' }"
@mousedown="startDragging"
@mouseup="stopDragging"
>
<!-- Your modal content here -->
</div>
</UModal>
</template>
<script setup>
import { ref } from 'vue'
import { useMouse, useEventListener } from '@vueuse/core'
const isOpen = ref(false)
const modalContent = ref(null)
const isDragging = ref(false)
const { x, y } = useMouse()
const startDragging = () => {
isDragging.value = true
}
const stopDragging = () => {
isDragging.value = false
}
useEventListener(window, 'mousemove', (event) => {
if (isDragging.value && modalContent.value) {
modalContent.value.style.left = `${event.clientX}px`
modalContent.value.style.top = `${event.clientY}px`
}
})
</script>
This example uses the UModal component from Nuxt UI and adds dragging functionality to its content. The modal's position is controlled by the mouse position when dragging.
Remember to install and configure Nuxt UI and VueUse in your project:
- Install Nuxt UI:
npm install @nuxt/ui - Install VueUse:
npm i -D @vueuse/nuxt @vueuse/core - Add
@nuxt/uiand@vueuse/nuxtto yourmodulesinnuxt.config.ts