Youssef Mansour
Youssef Mansour

Reputation: 1

How to create Vue3 <script setup> infinite scroll in Vuetify v-Autocomplete component?

<template>
  <v-autocomplete
    v-model="selected"
    :items="suppliers"
    item-text="name"
    item-value="id"
    label="Search suppliers"
    :search-input.sync="search"
    return-object
    multiple
    autocomplete="off"
    ref="autocompleteRef"
    @scroll="handleScroll"
    @input="handleSearch"
  >
    <template v-slot:append-item>
      <div v-if="suppliers.length > 0" v-intersect="onIntersect" class="pa-4 teal--text">
        Loading more suppliers...
      </div>
    </template>
  </v-autocomplete>
</template>
<script setup>
import { ref, watch } from 'vue';
import { useCookie } from "@core/composable/useCookie";
import { BASE_URL } from "@/utils/apiConfig";

const selected = ref(null);
const suppliers = ref([]);
const perPage = 10;
let page = 1;
let search = '';
const accessToken = useCookie('accessToken').value;

const autocompleteRef = ref(null);

const getSuppliers = async () => {
  try {
    const apiUrl = `${BASE_URL}supplier_name_find?per_page=${perPage}&page=${page}&term=${search}`;
    const response = await fetch(apiUrl, {
      headers: {
        'Authorization': `Bearer ${accessToken}`
      }
    });
    if (!response.ok) {
      console.log('Network response was not ok');
    }
    const responseData = await response.json();
    const suppliersData = responseData.data;
    const supplierNames = suppliersData.map(supplier => supplier.name);
    if (page === 1) {
      suppliers.value = supplierNames;
    } else {
      suppliers.value = [...suppliers.value, ...supplierNames];
    }
    console.log('Suppliers:', suppliers.value);
  } catch (error) {
    console.error('Error fetching suppliers:', error);
  }
};

const onIntersect = (entries) => {
  if (entries.length > 0 && entries[0].isIntersecting && entries[0].target === entries[0].target.parentNode.lastElementChild) {
    page++;
    getSuppliers();
  }
};

const handleScroll = () => {
  const element = autocompleteRef.value;
  if (element) {
    const {scrollTop, clientHeight, scrollHeight} = element;
    if (scrollTop + clientHeight >= scrollHeight - 10 && !is_loading_more.value) {
      page++;
      is_loading_more.value = true; // Set loading flag to true
      getSuppliers(); // Fetch more data
    }
  }
};


const handleSearch = (event) => {
  search = event.target.value;
  page = 1;
  getSuppliers();
};

watch(() => search, () => {
  page = 1;
  getSuppliers();
});
</script>

I'm using vue 3 with the vuetify library to create infinite scroll with V-Autocomplete but it's not working.. the data are {name and id}.

the request is sent when I'm writing inside the v-autocomplete and the data showing in the list to select one of the item(s). what I want is when I reach the bottom of the list send another request to fetch more data and increment the page..

Upvotes: 0

Views: 208

Answers (0)

Related Questions