Skip to content

Instantly share code, notes, and snippets.

@irozgar
Last active March 17, 2022 21:43
Show Gist options
  • Save irozgar/8927b610fed1f72facb9009b3f0688d7 to your computer and use it in GitHub Desktop.
Save irozgar/8927b610fed1f72facb9009b3f0688d7 to your computer and use it in GitHub Desktop.
Searchable select with menuselect and vue
<script setup>
import { ref, watch } from 'vue';
const options = [
"Barcelona",
"Madrid",
"Sevilla",
"Valencia",
"Vitoria",
"La Rioja",
];
const filteredOptions = ref([...options]);
const searchTerm = ref("");
const selectedOption = ref("Barcelona");
watch(searchTerm, (newValue) => {
filteredOptions.value = options.filter((option) => option.toLowerCase().includes(newValue.toLowerCase()));
});
function selectOption($event) {
selectedOption.value = $event.target.value
}
</script>
<template>
<p>Selected value: {{ selectedOption }}</p>
<p>Filtered options: {{ filteredOptions }} </p>
<selectmenu @change="selectOption($event)">
<div slot="listbox">
<popup behavior="listbox">
<input type="text" @change.stop v-model="searchTerm" />
<option v-for="option in filteredOptions">{{ option }}</option>
</popup>
</div>
</selectmenu>
</template>
<script>
// Using vue Options API
import { defineComponent } from "vue";
const options = [
"Barcelona",
"Madrid",
"Sevilla",
"Valencia",
"Vitoria",
"La Rioja",
];
export default defineComponent({
data() {
return {
options,
searchTerm: "",
selectedOption: options[0] || undefined,
}
},
methods: {
selectOption($event) {
this.selectedOption = $event.target.value;
},
},
computed: {
filteredOptions() {
return options.filter((option) => option.toLowerCase().includes(this.searchTerm.toLowerCase()));
}
}
})
</script>
<template>
<p>Selected value: {{ selectedOption }}</p>
<p>Filtered options: {{ filteredOptions }} </p>
<selectmenu @change="selectOption($event)">
<div slot="listbox">
<popup behavior="listbox">
<input type="text" v-model="searchTerm" />
<option v-for="option in filteredOptions">{{ option }}</option>
</popup>
</div>
</selectmenu>
</template>
@irozgar
Copy link
Author

irozgar commented Mar 17, 2022

A simple POC of a searchable select using the HTML element selectmenu. It's an experimental element available in Chrome Canary by enabling Experimental Web Platform features in about:flags.

More info an some examples here: https://css-tricks.com/the-selectmenu-element/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment