I need to implement a feature that automatically scrolls to the top of a scrollable list every time the search input is changed. Currently, I have a list where multiple items can be selected, and I want it to reset to the top whenever a new search query is entered.
For example, if I type 'b' in the search bar and then scroll down, typing 'e' should bring me back to the very top of the list.
Below is an example code snippet demonstrating what I am trying to achieve. I have attempted two different methods using the scrollTop property of the HTML element and the goTo function from Vuetify, but neither approach has been successful so far.
Code demo -
In case the demo link expires, here is the actual code:
<div id="app">
<v-app>
<v-main class="py-3 px-5">
<h1 class="teal--text">AutoComplete Infinite Scroll Example</h1>
<v-autocomplete
id="autoComplete"
ref="autoComplete"
v-model="selected"
:items="beers"
item-text="name"
item-value="id"
:search-input.sync="search"
label="Search the beers.."
return-object
multiple
autocomplete="off"
>
<template v-slot:append-item>
<div v-intersect="onIntersect" class="pa-4 teal--text">
Loading more items ...
</div>
</template>
</v-autocomplete>
</v-main>
</v-app>
new Vue({
el: '#app',
vuetify: new Vuetify(),
data() {
return {
search:'',
beers: [],
selected: null,
perPage: 30,
page: 1,
}
},
methods: {
getBeers() {
console.log('page', this.page)
const apiUrl = `https://api.punkapi.com/v2/beers?page=${this.page}&per_page=${this.perPage}`
axios.get(apiUrl)
.then(response => {
this.beers = [
...this.beers,
...response.data
]
})
},
onIntersect () {
console.log('load more...')
this.page += 1
this.getBeers()
},
},
watch:{
search:function(){
//first method
let myId=document.getElementById('autoComplete')
if(myId){
myId.scrollTop = 0
}
//second method with ref and vuetify goto
this.$nextTick(() => {
this.$vuetify.goTo(this.$refs.autoComplete)
})
}
},
created() {
this.getBeers()
}
})