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.
我正在尝试将下拉列表中的选定项添加到新数组中,并将其显示在页面上。我在输入栏上做了一个onblur事件,目的是在我点击外部时隐藏下拉菜单,但现在我无法选择项目,因为它们也在输入之外。因此,我尝试通过@click.top事件停止传播。但失败了。因此,现在我无法选择这些项并将其添加到选定的数组中。
<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.
我在输入栏上做了一个onblur事件,目的是在我点击外部时隐藏下拉菜单,但现在我无法选择项目,因为它们也在输入之外。因此,我尝试通过@click.top事件停止传播。但失败了。因此,现在我无法选择这些项并将其添加到选定的数组中。
更多回答
Try adding .stop
to your <p>
tag instead of the parent div
.
尝试将.stop添加到您的标记而不是父div。
Thank you kind, but it didn't help )
谢谢你的好意,但它没有帮助)
优秀答案推荐
Issue with @blur
directive: Wrap your input
and fruit list div
in a div
. e.g.
@blur指令的问题:将您的输入和水果列表div包装在一个div中。例如:
<div @blur="optionsVisible = false">
<input
type="text"
v-model="input"
placeholder="Search fruits..."
@input="optionsVisible = true"
/>
<div
class="item fruit"
v-if="optionsVisible"
v-for="fruit in filteredList()"
:key="fruit"
>
<p @click="select">{{ fruit }}</p>
</div>
</div>
If you just want to push the name of the fruit to the selected[]
you should write your function like this:
如果您只想将水果的名称推送到选定的[],则应该将函数编写如下:
<script setup>
import { ref } from "vue";
let selected = ref([]); // better to use const
let select = (e) => {
selected.value.push(e.srcElement.textContent);
}; // better if you use const
</script>
更多回答
我是一名优秀的程序员,十分优秀!