autocomplete

This commit is contained in:
2022-09-22 14:34:38 +02:00
parent d08fe3637b
commit 9a7bcf49fb

View File

@@ -7,7 +7,7 @@
> >
Type the name of a country to search Type the name of a country to search
</label> </label>
Lenght : {{searchCountries.length}}
<input <input
type="text" type="text"
id="search" id="search"
@@ -21,15 +21,15 @@
class="w-full rounded bg-white border border-gray-300 px-4 py-2 space-y-1 absolute z-10" class="w-full rounded bg-white border border-gray-300 px-4 py-2 space-y-1 absolute z-10"
> >
<li class="px-1 pt-1 pb-2 font-bold border-b border-gray-200"> <li class="px-1 pt-1 pb-2 font-bold border-b border-gray-200">
Showing {{ searchCountries.length }} of {{ countries.length }} results Showing {{ searchCountries.length }}
</li> </li>
<li <li
v-for="country in searchCountries" v-for="country in searchCountries"
:key="country.name" :key="country.properties.label"
@click="selectCountry(country.name)" @click="selectCountry(country.properties.label)"
class="cursor-pointer hover:bg-gray-100 p-1" class="cursor-pointer hover:bg-gray-100 p-1"
> >
{{ country.name }} {{ country.properties.label }}
</li> </li>
</ul> </ul>
@@ -44,43 +44,33 @@
</template> </template>
<script> <script>
import countries from '../data/countries.json' import {ref, computed, watch} from 'vue'
import {ref, computed} from 'vue'
export default { export default {
setup() { setup() {
let searchTerm = ref('') let searchTerm = ref('')
let searchCountries = ref('')
async function addressSearch (query) { async function addressSearch (query) {
return await fetch('https://api-adresse.data.gouv.fr/search/?q='+query) return await fetch('https://api-adresse.data.gouv.fr/search/?q='+query)
.then(function (response) { .then(function (response) {
return response.json(); return response.json();
}).then(function (jsonObj) { }).then(function (jsonObj) {
return jsonObj; return jsonObj.features;
}); });
} }
const searchCountries = computed(() => { watch(searchTerm, (selection, prevSelection) => {
if (searchTerm.value === '') { console.log(selection)
return [] searchCountries= addressSearch(searchCountries)
}
console.log(addressSearch)
let matches = 0
return countries.filter(country => {
if (country.name.toLowerCase().includes(searchTerm.value.toLowerCase()) && matches < 10) {
matches++
return country
}
}) })
});
const selectCountry = (country) => { const selectCountry = (country) => {
selectedCountry.value = country selectedCountry.value = country
searchTerm.value = '' searchTerm.value = ''
} }
let selectedCountry = ref('') let selectedCountry = ref('')
return { return {
countries,
searchTerm, searchTerm,
searchCountries, searchCountries,
selectCountry, selectCountry,