Making Parent Items Selectable in PrimeVue Dropdown with Groups

26 Views Asked by At

I'm working with PrimeVue's Dropdown component to render a hierarchical list of options grouped by country, with cities as child items. My data structure includes countries as parent labels and their cities as items. Here's a simplified version of my setup:

<script setup>
import { ref } from "vue";
import Dropdown from 'primevue/dropdown';

const selectedCity = ref();
const groupedCities = ref([
    {
        label: 'Germany',
        code: 'DE',
        items: [
            { label: 'Berlin', value: 'Berlin' },
            { label: 'Frankfurt', value: 'Frankfurt' },
            { label: 'Hamburg', value: 'Hamburg' },
            { label: 'Munich', value: 'Munich' }
        ]
    },
    {
        label: 'USA',
        code: 'US',
        items: [
            { label: 'Chicago', value: 'Chicago' },
            { label: 'Los Angeles', value: 'Los Angeles' },
            { label: 'New York', value: 'New York' },
            { label: 'San Francisco', value: 'San Francisco' }
        ]
    },
    {
        label: 'Japan',
        code: 'JP',
        items: [
            { label: 'Kyoto', value: 'Kyoto' },
            { label: 'Osaka', value: 'Osaka' },
            { label: 'Tokyo', value: 'Tokyo' },
            { label: 'Yokohama', value: 'Yokohama' }
        ]
    },
    {
        label: 'Myanmar',
        code: 'MM',
        items: []
    }
]);
</script>

In the Dropdown, I'm using the optionGroupLabel for country labels and optionGroupChildren for cities. My requirement is for users to be able to select a country (parent label) directly if it has no cities listed (empty items array). However, with my current setup, only cities (child items) are selectable, and countries with empty city lists cannot be selected.

I've attempted to modify the structure and utilize custom templates within the Dropdown component. Still, I'm struggling to make parent items (countries with no cities) selectable and display them correctly in the dropdown box upon selection.

Here's a brief overview of my component:

<template>
    <div class="card flex justify-content-center">
        <Dropdown v-model="selectedCity" :options="groupedCities" optionLabel="label" optionGroupLabel="label"
            optionGroupChildren="items" placeholder="Select a City" class="w-full md:w-14rem">
        </Dropdown>
    </div>
</template>

Could anyone advise on how to make parent items selectable in this scenario? Specifically, I need to ensure that when a parent item with an empty items array is selected, it is displayed as the selected value in the dropdown.

Thank you for any guidance or solutions you can provide!

0

There are 0 best solutions below