0

I am looking to have a dropdown v-autocomplete to return the filtered results in reverse. For example the items in the dropdown would be [2.10, 2.9, 1.11, 1.10, 1.9, 1.6, 1.1]. When a user types 1.1 for example I would need the results to return in reverse (ascending order) such as [1.1, 1.10, 1.11] instead of the descending order.

Here is what I tried:

     <v-autocomplete
        v-model="searchText"
        :items="items"
        label="search"
        :search-input.sync="filter"
        ref="selectExample"
      >
      </v-autocomplete>

Then the script part is:

export default {
  data() {
    return {
      searchText: '',
      filter: '',
      watch: {
        filter() {
          this.filteredItems = this.$refs['selectExample'].filteredItems.reverse()
        },
      }
    }
  }
}

Unfortunately this only reverses the order of items on the dropdown and doesn't reverse the order of the searched items. I have tried using filter as well but the filtered results just can't be modified it seems. Also when the search is cleared it should reset and show all the items again as before in descending order. Any help is appreciated thanks!

JC Lopez
  • 243
  • 1
  • 2
  • 12

1 Answers1

0

I would use two arrays, one maintains the original values and sorting order, the other is bound to the v-autocomplete and is a filtered version of the original array based on whatever the search text is.

<v-autocomplete
  v-model="select"
  :items="items"
  :search-input.sync="filter"
  label="Filter"
></v-autocomplete>
data () {
  return {
    select: null,
    filter: null,
    items: [],
    values: ['1.11', '1.10', '1.9', '1.6', '1.1'],
  }
},
watch: {
  filter (val) {
    val && val !== this.select && this.querySelections(val)
  },
},
methods: {
  querySelections (v) {
    this.items = this.values.filter(i => i.includes(v)).reverse()
  }
},

codepen

You have to use string values for values array, otherwise JavaScript automatically strips the trailing 0 from numbers like 1.10 so it becomes 1.1.

yoduh
  • 7,074
  • 2
  • 11
  • 21
  • When I click on dropdown can't see any items showing, you answer is very close just needs to be able to show initially all the items on the dropdown. It should also reset the search too if you clear it and show again the initial values in descending order again. Also we can add '2.10', '2.9' to the values to showcase how 2.9 won't be shown if a 1 is typed but 2.10 should show up. – JC Lopez Jun 26 '23 at 18:50