I'm trying to add the selected item from a dropdown list to a new array and display it on the page. I did a onblur event on input field in purpose to hide the dropdown when I click outside, but now I can't select the items ,cause they are also outside the input. So I've tryed to stop propagation via @click.stop event. And failed. So now I can't select the items and add it to the selected array.
<template>
<input
type="text"
v-model="input"
placeholder="Search fruits..."
@blur="optionsVisible = false"
@input="optionsVisible = true"
/>
<div
class="item fruit"
v-if="optionsVisible"
v-for="fruit in filteredList()"
:key="fruit"
@click.stop=""
>
<p @click="select">{{ fruit }}</p>
</div>
<div class="item error" v-if="input && !filteredList().length">
<p>No results found!</p>
</div>
<div class="selected">Selected: {{ selected }}</div>
</template>
<script setup>
import { ref } from 'vue';
let input = ref('');
let optionsVisible = ref(false);
let selected = ref([]); // fill this array with selected items from the dropdown
let select = (e) => {
selected.push(e);
};
const fruits = ['apple', 'banana', 'orange'];
function filteredList() {
return fruits.filter((fruit) =>
fruit.toLowerCase().includes(input.value.toLowerCase())
);
}
</script>
I did a onblur event on input field in purpose to hide the dropdown when I click outside, but now I can't select the items ,cause they are also outside the input. So I've tryed to stop propagation via @click.stop event. And failed. So now I can't select the items and add it to the selected array.
Issue with
@blurdirective: Wrap yourinputand fruit listdivin adiv. e.g.If you just want to push the name of the fruit to the
selected[]you should write your function like this: