Building Dynamic List Views with Expandable Details in Vue 3

In Vue 3, it is common to dynamically show additional details of a list item when clicked. Using the v-for directive to iterate over a list, we can display nested details by toggling their visibility. Below is an example to illustrate this functionality.

Implementation Steps

  1. Iterate Over a List: Use v-for to render each item as a list element.
  2. Toggle Details Visibility: Add a property (e.g., showBags) to manage the visibility of subdetails for each list item.
  3. Bind Click Events: Use @click to toggle the visibility of the subdetails when the list item is clicked.

Code Example

<div v-for="(item, index) in displayResults" :key="item.id">
    <li @click="toggleItemDetails(index)"
        class="cursor-pointer border p-4 mb-4 rounded-lg shadow-md flex items-center space-x-6 bg-white hover:bg-gray-100">
        <div class="w-full sm:w-1/5">
            <p class="text-xs text-gray-500">Item Name:</p>
            <p class="text-sm font-semibold">{{ item.name || "N/A" }}</p>
        </div>
    </li>

    <!-- Subdetails Section -->
    <div v-if="item.showDetails" class="overflow-x-auto">
        <div v-if="item.subDetails?.length > 0" class="max-h-64 overflow-y-auto p-4 rounded-md shadow-sm">
            <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
                <div v-for="detail in item.subDetails" :key="detail.id"
                    class="bg-white border p-2 rounded-md text-center shadow-md">
                    <p>
                        <span class="text-xs text-gray-500">Detail Info:</span>
                        <span class="text-sm font-semibold">{{ detail.info || "N/A" }}</span>
                    </p>
                </div>
            </div>
        </div>
        <div v-else class="no-items text-center pt-5 text-lg mt-6">No details to display</div>
    </div>
</div>

Explanation

  • v-for Directive: Renders each item in the displayResults array.
  • Click Event: The @click event calls toggleTreeDetails(index), toggling the showBags property for the clicked item.
  • Dynamic Visibility: The v-if="tree.showBags" condition dynamically shows or hides the subdetails.

This approach keeps the UI clean and interactive, only displaying details when needed.

Leave a comment

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