如何通过Vuetify v-autocomplete的#clear插槽元素清除输入内容?
解决Vuetify v-autocomplete自定义清除图标点击无效问题
问题分析
使用#clear插槽自定义v-autocomplete的清除按钮时,仅手动设置v-model为null无法完全触发组件的清除逻辑——组件内部还有过滤状态、输入框显示值等需要同步重置,且自定义元素的点击事件未正确关联组件的内置清除方法。
解决方案
方案1:直接使用插槽提供的内置clear方法
Vuetify的#clear插槽默认会传递一个clear方法,绑定到自定义按钮的点击事件即可,无需手动处理v-model:
<template> <v-autocomplete ref="searchInput" v-model="inputVal" clearable label="Placeholder" :items="items" variant="outlined" :class="$style['text-input']"> <!-- 接收插槽参数中的clear方法,直接绑定点击事件 --> <template #clear="{ clear }"> <button type="button" @click="clear">X</button> </template> </v-autocomplete> </template> <script lang="ts"> type SearchItem = { value: number | string title: string } export type Props = { searchFieldPlaceholderText: string } </script> <script setup lang="ts"> import { ref } from "vue" const inputVal = ref<number | string | undefined>() const searchInput = ref<any>() const items: Array<SearchItem> = [ { title: "Item 1", value: 1, }, { title: "Item 2", value: 2, }, ] </script> <style lang="scss" module> .text-input { max-width: 400px; } </style>
方案2:手动调用组件实例的clear方法
如果需要自定义清除逻辑,除了设置v-model外,还需调用组件实例的clear()方法同步内部状态:
<template> <v-autocomplete ref="searchInput" v-model="inputVal" clearable label="Placeholder" :items="items" variant="outlined" :class="$style['text-input']"> <template #clear> <button type="button" @click="clearInput">X</button> </template> </v-autocomplete> </template> <script lang="ts"> type SearchItem = { value: number | string title: string } export type Props = { searchFieldPlaceholderText: string } </script> <script setup lang="ts"> import { ref } from "vue" const inputVal = ref<number | string | undefined>() const searchInput = ref<any>() const items: Array<SearchItem> = [ { title: "Item 1", value: 1, }, { title: "Item 2", value: 2, }, ] const clearInput = () => { inputVal.value = null // 调用组件实例的clear方法同步内部状态 searchInput.value?.clear() } </script> <style lang="scss" module> .text-input { max-width: 400px; } </style>
关键说明
- 插槽提供的
clear方法会完整处理组件的清除逻辑,包括重置v-model、清空输入框、重置过滤状态等。 - 仅设置v-model为
null无法同步组件内部的所有状态,可能导致输入框仍显示旧值或过滤状态未重置。
内容的提问来源于stack exchange,提问作者FieryRider
相关产品推荐
相关产品推荐

