Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

scrollTo doesn't seem to work with dynamically added list items #8

Open
linkurzweg opened this issue Oct 25, 2023 · 0 comments
Open

Comments

@linkurzweg
Copy link

Hello! First of all thanks a lot for creating this component :)

The list itself seems to work great, but I can't get the scrollTo method to work. I'm fetching data from an API and adding the fetched items dynamically to the list. My code looks like this currently:

<template>
  <div class="list">
    <VirtualScroller ref="scroller" :default-size="170" :items="searchResult?.items ?? []" :padding="20">
      <template #item="{ ref: searchResultItem }">
        <ListItem :item="searchResultItem!" />
      </template>
    </VirtualScroller>
    <p v-if="indexValid">
      <button
        type="button"
        aria-label="Load more search results"
        @click="fetchNextPage"
      >
        {{ $t('show-more') }}
      </button>
    </p>
  </div>
  <template v-if="isLoading && !searchResult?.items?.length">
    <Loader />
  </template>
</template>

<script setup lang="ts">
  import { ListItem, Loader } from '@/components'
  import { useStore } from '@/store'
  import { storeToRefs } from 'pinia'
  import { computed, ref, watch } from 'vue'
  import { createVirtualScroller } from 'vue-typed-virtual-list'
  import { InternalQueryResultItemDto } from '@/models'

  const VirtualScroller = createVirtualScroller<InternalQueryResultItemDto>()

  const store = useStore()
  const { searchResult, isLoading } = storeToRefs(store)

  type VirtualListInstance = InstanceType<typeof VirtualScroller>
  const scroller = ref<VirtualListInstance | null>(null)

  const indexValid = computed(() => {
    if (typeof searchResult.value?.page === 'number' && typeof searchResult.value?.pageCount === 'number') {
      return searchResult.value?.page < searchResult.value?.pageCount - 1
    }

    return false
  })

  const fetchNextPage = () => {
    if (typeof searchResult.value?.page === 'number') {
      store.fetchAndUpdateSearchResult(searchResult.value?.page + 1, 10, true)
      scroller.value?.scrollTo((searchResult.value?.page + 1) * 10 + 1)
    }
  }
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant