#How do I make a draggable modal in Nuxt?

3 messages · Page 1 of 1 (latest)

viral summitBOT
#

Hi @low kiln. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

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:

  1. First, use the Modal component from Nuxt UI as a base for your modal:

Modal (https://ui.nuxt.com/components/modal)

  1. To make the modal draggable, you can use the useMouse composable 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:

#
  1. Install Nuxt UI: npm install @nuxt/ui
  2. Install VueUse: npm i -D @vueuse/nuxt @vueuse/core
  3. Add @nuxt/ui and @vueuse/nuxt to your modules in nuxt.config.ts

Note that this is a basic implementation and you might need to adjust it based on your specific requirements, such as constraining the draggable area or adding smooth animations.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: