headlessui Combobox with fetching data Hello everybody, Im trying to make a searchable input with results of data. My problem with combobox is when i click the ComboboxOption the data dont show to input but query variable get the data.
template>
<Combobox v-model="query">
<div class="relative mt-1 w-96">
<div class="relative w-full cursor-default overflow-hidden rounded-lg bg-white text-left shadow-md focus:outline-none focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-opacity-75 focus-visible:ring-offset-2 focus-visible:ring-offset-teal-300 sm:text-sm">
<ComboboxInput
class="w-full border-none py-2 pl-3 pr-10 text-sm leading-5 text-gray-900 focus:ring-0"
:displayValue="(city) => city.place_name"
@change="query = $event.target.value"
@input="getPlaces"
placeholder="Search for a city or a state"
/>
</div>
<ComboboxOptions v-if="places" class="mt-1 max-h-60 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm">
<ComboboxOption
v-for="searchResult in places"
as="template"
:key="searchResult.id"
:value="searchResult"
v-slot="{ selected, active }"
>
<li
class="relative cursor-default select-none py-2 pl-2 pr-4"
:class="{
'bg-blue-600 text-white': active,
'text-gray-900': !active,
}"
>
<span
class="block truncate"
:class="{ 'font-medium': selected, 'font-normal': !selected }"
>
{{ searchResult.place_name }}
</span>
</li>
</ComboboxOption>
</ComboboxOptions>
</div>
</Combobox>
</template>
<script setup>
import { ref } from 'vue';
import {
Combobox,
ComboboxInput,
ComboboxOptions,
ComboboxOption,
} from '@headlessui/vue'
const mapboxAPIKey = 'pk.eyJ1Ijoiam9obmtvbWFybmlja2kiLCJhIjoiY2t5NjFzODZvMHJkaDJ1bWx6OGVieGxreSJ9.IpojdT3U3NENknF6_WhR2Q'
const query = ref('')
const timeout = ref()
const places = ref()
const error = ref()
const getPlaces = () => {
clearTimeout(timeout.value)
timeout.value = setTimeout(async () => {
if (query.value !== '') {
try {
const responce = await axios.get(`https://api.mapbox.com/geocoding/v5/mapbox.places/${query.value}.json?access_token=${mapboxAPIKey}&types=place`)
places.value = responce.data.features
} catch {
error.value = true
}
return
}
places.value = null
}, 300)
}
</script>
I think the issue is that you are modeling the Combobox component to your query ref. You should instead bind a ref variable to represents the selected item. So in your example that could be selectedPlace, or in a more generic implementation, selectedItem.
Please sign in or create an account to participate in this conversation.