如何将搜索栏中选定的 Item 添加到新的 vue3 js 数组中?

问题描述 投票:0回答:1

我正在尝试将下拉列表中的所选项目添加到新数组中并将其显示在页面上。我在输入字段上执行了 onblur 事件,目的是在单击外部时隐藏下拉列表,但现在我无法选择项目,因为它们也在输入之外。所以我尝试通过 @click.stop 事件停止传播。但失败了。所以现在我无法选择项目并将其添加到选定的数组中。

<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>

我在输入字段上执行了 onblur 事件,目的是在单击外部时隐藏下拉列表,但现在我无法选择项目,因为它们也在输入之外。所以我尝试通过 @click.stop 事件停止传播。但失败了。所以现在我无法选择项目并将其添加到选定的数组中。

javascript vue.js input vuejs3 stoppropagation
1个回答
0
投票

关于

@blur
指令的问题:将您的
input
水果清单
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>

如果您只想将水果的名称推送到

selected[]
,您应该这样编写函数:

<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>
© www.soinside.com 2019 - 2024. All rights reserved.