oswinso
oswinso

Reputation: 273

Clear search box after selecting with vuetify autocomplete

I'm trying to use the vuetify autocomplete component, but I can't figure out how to clear the search box after selecting an item. I've tried to use the input event to clear the model bound in v-model, and while it does work the first time I select an item, the search box does not get cleared afterwards.

//App.Vue
<v-autocomplete
      // Other stuff
      v-model="model"
      :search-input.sync="searchInput"
      v-on:input="addClass">
    </v-autocomplete>\

// methods
addClass (a) { 
  this.model = ""
}

Upvotes: 16

Views: 20719

Answers (6)

Iceflower S
Iceflower S

Reputation: 194

In Vuetify 3 you can use the property clear-on-select in combination with multiple to clear the written text.

Upvotes: 5

Navjot Singh Prince
Navjot Singh Prince

Reputation: 21

<script setup>

 //Variables
const usersList = ref([
 { id:1, name: "Prince", city: "ferozepur" },
 { id:2, name: "Navjot", city: "ferozepur cantt" },
]);

const search = ref(null);

//For clear search text fields
const ACRef = ref(null);
const blurEvent = new Event("blur");

watch(search, (item) => {
  if (!item) search.value = null;
  if (item && typeof item === "object") {

    //for clear search text
    ACRef.value?.dispatchEvent(blurEvent);

    let { name, city } = item;

    //check for duplicate user
    const alreadyExist = userStore.UserList.find((item) => item.id === id);
    if (alreadyExist) {
      search.value = null;
      return;
    }

    //if unique user
    userStore.UserList.push({
      name: name,
      city: city,
    });
    search.value = null;
  }
});
</script>


 //Here is Template Vuetify3 Code
 <VCol cols="12" md="6">
  <v-autocomplete
     ref="ACRef"
     v-model="search"
     placeholder="Search Existing User"
     persistent-placeholder
     :items="usersList"
     item-title="name"
     return-object
   />
</VCol>

Enjoy !

Upvotes: 0

Sinisa Rudan
Sinisa Rudan

Reputation: 988

Here is a tested solution, made in Vue 3 with the Composition API and with Vuetify 3:

     <v-autocomplete
            ref="addClassAC"
            v-model="selectedClass"
            :items="classes"
            @update:modelValue="addClass"
        ></v-autocomplete>

I've added :items="classes" as a list to populate your v-autocomplete. You are reacting on event update:modelValue update:modelValue: Event that is emitted when the component’s model changes. More at: https://vuetifyjs.com/en/api/v-autocomplete/#events

I've also changed your model to selectedClass. Try not to use names that might be reserved (Vue might break without good explanation in these cases) and also use names that better describe the usage of the variable.

Here is the code in typescript. I've provided comments in the code:

<script setup lang="ts">
import { ref } from "vue";

/** selectedClass holds the selection */
const selectedClass = ref<string>();

/** addClassAC enables us to reference the autocomplete from the code. 
It is linked through `ref="addClassAC"` in the HTML code */
const addClassAC = ref<HTMLElement | null>(null);

  const blurEvent: Event = new Event('blur');

  const addClass = (selectetion:any) => {
  console.log("[addClass]", selectetion);

  //TODO: use the selected value `selectetion` for whatever you need
  // ...

  // resetting the value of the selector after it is selected, 
  // so that the new selection can be done:
  selectedClass.value = undefined;

  // we dispatch `blur` (unfocus) event over our autocomplete component 
  // (referenced / linked between html and code):
  addClassAC.value?.dispatchEvent(blurEvent);
}

</script>

JavaScript version provided in comment.

Upvotes: 1

breilly
breilly

Reputation: 19

Ran into the same issue with v-combobox and found a simple solution. Haven't tested for v-autocomplete but would guess this solution will work as well.

For v-combobox components, reset the component's lazySearch value. An example looks like this:

<v-combobox
  ref="el"
  :items="items"
  chips
  clearable
  deletable-chips
  multiple
  outlined
  @change="reset"
></v-combobox>

<script>
export default {
  methods: {
    reset() {
      this.$refs.el.lazySearch = ''
    }
}
</script>

Upvotes: 1

Bill
Bill

Reputation: 530

I have the same question as well, and tried Antoine answer with no luck.

Checked in Vue plug-in in my environment, the issue seem to be caused by the event sequence.

After event change emit by <VAutocomplete>, there are another event update:search-input also emit by <VAutocomplete>, and from the payload it seem to setting the value to what u just cleared in change event and so it look like you cannot clear the value.

After many try I managed to pull out one workable code which you can find the example below, which based on Antoine solution with a few changes:

  1. $nextTick used
  2. On top of the search-input variable, also clear the variable bind to v-model

new Vue({
    el: '#app',
    vuetify: new Vuetify(),
    
    data: () => ({
      searchResult: null,
      searchString: '',
      items: ['one', 'two', 'three'],
      selected: '',
    }),
    
    methods: {
      itemChange(e) {
        this.selected = e;
        this.$nextTick(() => {
          this.searchString = '';
          this.searchResult = null;
        });
      },
    },
  })
  
Vue.config.productionTip = false
Vue.config.devtools = false
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet">
  
<div id="app">
  <v-app>
    <v-content>
      <v-container>

        <v-autocomplete
          v-model="searchResult"
          :items="items"
          :search-input.sync="searchString"
          label="Search..."
          clearable
          @change="itemChange"
        ></v-autocomplete>
        <div>{{ `Selected: ${selected}` }}</div>

      </v-container>
    </v-content>
  </v-app>
</div>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.js"></script>

Upvotes: 12

Antoine Viscardi
Antoine Viscardi

Reputation: 890

To achieve this you need to set your searchInput variable to an empty string on the change event. Your code would look something like this,

// App.Vue
<v-autocomplete
      // Other stuff
      v-model="model"
      :search-input.sync="searchInput"
      @change="searchInput=''"
></v-autocomplete>

Upvotes: 23

Related Questions