Displaying Detailed Pop-Ups on Click in Vue 3

Pop-ups are essential for displaying additional details without navigating away from the current view. Vue 3 simplifies creating pop-ups by dynamically binding visibility and data to a modal component.

Implementation Steps

  1. Set Up a Data Property: Create a property like showDiamondDetails to track modal visibility.
  2. Display Modal on Click: Use an event handler (e.g., @click) to set the property to true and populate modal data.
  3. Close Modal: Add a button or area to reset the visibility property.

Code Example

<div v-if="showDetailsModal"
    class="fixed inset-0 flex items-center justify-center bg-black bg-opacity-15 backdrop-blur-sm">
    <div class="bg-white p-6 rounded-lg shadow-lg w-3/4 sm:w-1/2">
        <h2 class="text-lg font-semibold mb-4">Details</h2>
        <div v-if="selectedItem?.details?.length > 0">
            <table class="table-auto w-full border-collapse border border-gray-300">
                <thead>
                    <tr class="bg-gray-200">
                        <th class="border px-4 py-2">Attribute</th>
                        <th class="border px-4 py-2">Value</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="detail in selectedItem.details" :key="detail.id">
                        <td class="border px-4 py-2">{{ detail.attribute }}</td>
                        <td class="border px-4 py-2">{{ detail.value }}</td>
                    </tr>
                </tbody>
            </table>
        </div>
        <div v-else>No details available for this item.</div>
        <button @click="closeDetailsModal" class="mt-4 bg-red-500 text-white px-4 py-2 rounded">Close</button>
    </div>
</div>

Explanation

  • Dynamic Visibility: The v-if="showDiamondDetails" condition controls whether the modal is shown.
  • Event Handlers:
  • @click="showDiamondDetailsForBag(bag)" populates the selectedBag data and opens the modal.
  • @click="closeDiamondDetails" closes the modal.
  • Styling and Interaction: The modal uses utility classes for positioning and styling, creating a polished user experience.

By combining v-if and event handlers, you can efficiently create and manage pop-ups in your Vue 3 applications.

Leave a comment

Your email address will not be published. Required fields are marked *