You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Headless UI Combobox(自动完成):多选后如何清空输入框?

解决Headless UI Combobox多选后清空输入框的问题

方法一:利用Combobox的@select事件

直接在Combobox组件上绑定@select事件,选中选项时清空查询值,同时确保输入框与查询值双向绑定:

修改后的模板代码:

<template>
  <Combobox v-model="selectedUsers" multiple @select="clearInput">
    <!-- ... 其他组件内容 ... -->
    <ComboboxInput
      v-model="query"
      :displayValue="(user) => user.name"
      class="w-full text-sm py-2 focus:outline-none focus-visible:outline-none rounded-lg"
      placeholder="Mitarbeiter hinzufügen..."
    />
    <!-- ... 其他组件内容 ... -->
  </Combobox>
</template>

对应的脚本部分:

<script setup>
// ... 导入内容 ...

const selectedUsers = ref([]);
const query = ref('');

const clearInput = () => {
  query.value = '';
};

// ... 其他脚本代码 ...
</script>

方法二:监听选中项变化(兼容多选增删场景)

如果@select事件不生效,可以通过监听selectedUsers的变化,当新增选中项时清空输入框:

<script setup>
// ... 导入内容 ...
import { watch } from 'vue';

const selectedUsers = ref([]);
const query = ref('');

watch(selectedUsers, (newUsers, oldUsers) => {
  // 仅当新增选项时清空输入框
  if (newUsers.length > oldUsers.length) {
    query.value = '';
  }
}, { deep: true });

// ... 其他脚本代码 ...
</script>

关键说明

  • 替换原有的@change="query = $event.target.value"为v-model="query",确保输入框的值与query响应式双向绑定,这样修改query才能实时同步到输入框。
  • 若使用watch方式,开启deep: true是因为selectedUsers是数组类型,需要深度监听内部元素变化。

内容的提问来源于stack exchange,提问作者StormiCParK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 17:03:10