Cara menyesuaikan medan autolengkap/pilih untuk berfungsi dengan penapisan dan penomboran bahagian pelayan

WBOY
Lepaskan: 2024-09-04 16:36:24
asal
1030 orang telah melayarinya

How to adapt an autocomplete/select field to work with server-side filtering and pagination

pengenalan

Dalam pembangunan bahagian hadapan, terdapat banyak pilihan rangka kerja komponen yang menawarkan penyelesaian mudah kepada kebanyakan jenis masalah. Namun, selalunya, anda menemui isu yang memerlukan penyesuaian. Sesetengah rangka kerja membenarkan ini pada tahap yang lebih besar daripada yang lain, dan tidak semuanya sama mudah untuk disesuaikan. Vuetify ialah salah satu rangka kerja yang paling kaya dengan ciri dengan dokumentasi yang sangat terperinci. Walau bagaimanapun, dalam praktiknya, menyiasat beberapa fungsi yang kelihatan remeh dan menghasilkan penyelesaian yang dioptimumkan masih boleh mengambil masa yang ketara.

Mengenalpasti Cabaran

Komponen autolengkap Vuetify sangat mengagumkan. Ia memberi pengguna pelbagai pilihan apabila ia datang kepada penyesuaian, baik visual dan berfungsi. Walaupun sesetengah mod boleh dicetuskan dengan satu sifat, yang lain memerlukan lebih banyak usaha, dan cara penyelesaiannya tidak selalunya mudah. Dalam artikel ini, saya akan membincangkan penyelesaian saya untuk melaksanakan penapisan dan penomboran sebelah pelayan, dengan memanfaatkan konsep penatalan tak terhingga. Selain itu, teknik yang dibincangkan di sini juga boleh digunakan pada komponen v-select.

Penyelesaian: Peningkatan sisi pelayan

Dalam bab ini kami akan menggariskan penyelesaian kami untuk meningkatkan v-autolengkap dengan logik sebelah pelayan. Pertama, kami akan membungkusnya ke dalam komponen tersuai kami sendiri yang akan digunakan untuk membuat pelarasan selanjutnya. Menggunakan slot item tambahan terbina dalam digabungkan dengan arahan v-intersect Vuetify, kami akan melaksanakan apa yang dipanggil tatal tak terhingga. Ini bermakna kami hanya akan memuatkan segelintir rekod pada mulanya. Dengan kombinasi yang disebutkan di atas, kami akan mengesan apabila bahagian bawah senarai dicapai. Pada ketika itu, kami akan menghantar permintaan susulan secara automatik untuk memuatkan halaman rekod seterusnya, sehingga kami akhirnya sampai ke bahagian bawah.

Selepas itu, kami akan mengembangkan penyelesaian kami untuk memasukkan penapisan dengan membuat pelarasan pada sifat v-autolengkap, melumpuhkan penapisan bahagian hadapan, menambah penunjuk yang mencukupi dan mengendalikan kedudukan tatal untuk memastikan pengalaman yang lancar dan intuitif untuk pengguna akhir . Kami akan berakhir dengan sesuatu seperti ini:

How to adapt an autocomplete/select field to work with server-side filtering and pagination

Menetapkan Perkara

Pelaksanaan teknikal akan ditunjukkan dengan Vue, rangka kerja pilihan saya untuk kerja harian, digabungkan dengan Vuetify, rangka kerja komponen yang sangat teguh dan boleh disesuaikan yang biasa digunakan dalam ekosistem Vue. Harap maklum bahawa konsep yang digunakan di sini boleh digunakan menggunakan gabungan lain teknologi JavaScript yang popular.

Penyelesaian akan berbeza sedikit bergantung pada versi Vue dan Vuetify. Memandangkan versi 3.x kedua-duanya telah dikeluarkan untuk sekian lama dan kini menjadi piawaian industri, saya akan menggunakannya. Walau bagaimanapun, saya akan meninggalkan nota penting untuk Vue 2/Vuetify 2, kerana banyak projek aktif masih menggunakannya. Perbezaannya biasanya kecil, kecuali apabila ia datang untuk mengakses elemen Vuetify dalaman (yang lebih sukar dilakukan dalam Vue 3, kerana $refs tidak disokong).

Untuk bermula, kami akan mencipta projek kosong baharu. Anda boleh melangkau perenggan ini jika anda ingin menambahkan penyelesaian kepada projek sedia ada. Menggunakan Pengurus Pakej Node (NPM), kami akan mencipta projek dengan arahan: npm create vue@latest. Tetapan lalai adalah baik untuk tujuan kami, tetapi jika anda mahu, anda boleh menukarnya. Saya mendayakan pilihan ESLint dan Prettier. Terdapat cara lain untuk memulakan projek Vue, tetapi saya lebih suka yang ini kerana ia menggunakan Vite sebagai pelayan pembangunan secara lalai.

Seterusnya, kita perlu menambah Vuetify dan kebergantungan asas yang tidak termasuk di dalamnya. Melainkan anda memilih fon ikon lain atau memilih pilihan lain untuk CSS, anda boleh menjalankan ini: npm install vuetify @mdi/font sass. Mengikuti dokumentasi rasmi anda boleh menyediakan Vuetify dalam fail main.js. Jangan lupa baris fon jika anda menggunakan ikon MDI seperti saya.

// file: main.js
import './assets/main.css';

import { createApp } from 'vue';
import App from './App.vue';

import '@mdi/font/css/materialdesignicons.css';
import 'vuetify/styles';
import { createVuetify } from 'vuetify';
import { VAutocomplete } from 'vuetify/components';
import { Intersect } from 'vuetify/directives';

const vuetify = createVuetify({
  components: { VAutocomplete },
  directives: { Intersect }
});

createApp(App).use(vuetify).mount('#app');
Salin selepas log masuk

Untuk bahagian belakang kami, saya memilih untuk menggunakan perkhidmatan API percuma dengan data palsu yang dipanggil JSON Placeholder. Walaupun ia bukan sesuatu yang anda akan gunakan dalam apl pengeluaran, ia adalah perkhidmatan yang ringkas dan percuma yang boleh memberikan kami semua yang kami perlukan dengan pelarasan yang minimum.

Sekarang, mari kita selami proses pengekodan sebenar. Cipta fail Vue baharu di dalam direktori komponen. Namakannya bagaimanapun anda mahu - Saya memilih PaginatedAutocomplete.vue. Tambah bahagian templat yang mengandungi satu elemen v-autolengkap. Untuk mengisi elemen ini dengan data, kami akan mentakrifkan sifat rekod yang akan dihantar kepada komponen.

For some minor styling adjustments, consider adding classes or props to limit the width of the autocomplete field and its dropdown menu to around 300px, preventing it from stretching across the entire window width.

// file: PaginatedAutocomplete.vue
<template>
  <v-autocomplete :items="items" :menu-props="{ maxWidth: 300 }" class="autocomplete">
    <!--  -->
  </v-autocomplete>
</template>

<script setup>
defineProps({
  items: {
    type: Array,
    required: true
  }
});
</script>

<style lang="scss" scoped>
.autocomplete {
  width: 300px;
}
</style>
Salin selepas log masuk

In the App.vue file, we can delete or comment out the header and Welcome components and import our newly created PaginatedAutocomplete.vue. Add the data ref that will be used for it: records, and set its default value to an empty array.

// file: App.vue
<script setup>
import { ref } from 'vue';

import PaginatedAutocomplete from './components/PaginatedAutocomplete.vue';

const records = ref([]);
</script>

<template>
  <main>
    <PaginatedAutocomplete :items="records" />
  </main>
</template>
Salin selepas log masuk

Adjust global styles if you prefer. I changed the color scheme from dark to light in base.css and added some centering CSS to main.css.

That completes the initial setup. So far, we only have a basic autocomplete component with empty data.

Controlling Data Flow with Infinite Scroll

Moving forward, we need to load the data from the server. As previously mentioned, we will be utilizing JSON Placeholder, specifically its /posts endpoint. To facilitate data retrieval, we will install Axios with npm install axios.

In the App.vue file, we can now create a new method to fetch those records. It’s a simple GET request, which we follow up by saving the response data into our records data property. We can call the function inside the onMounted hook, to load the data immediately. Our script section will now contain this:

// file: App.vue
<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';

import PaginatedAutocomplete from './components/PaginatedAutocomplete.vue';

const records = ref([]);

function loadRecords() {
  axios
    .get('https://jsonplaceholder.typicode.com/posts')
    .then((response) => {
      records.value = response.data;
    })
    .catch((error) => {
      console.log(error);
    });
}

onMounted(() => {
  loadRecords();
});
</script>
Salin selepas log masuk

To improve the visual user experience, we can add another data prop called loading. We set it to true before sending the request, and then revert it to false after the response is received. The prop can be forwarded to our PaginatedAutocomplete.vue component, where it can be tied to the built-in v-autocomplete loading prop. Additionally, we can incorporate the clearable prop. That produces the following code:

// file: Paginated Autocomplete.vue
<template>
  <v-autocomplete
    :items="items"
    :loading="loading"
    :menu-props="{ maxWidth: 300 }"
    class="autocomplete"
    clearable
  >
    <!--  -->
  </v-autocomplete>
</template>

<script setup>
defineProps({
  items: {
    type: Array,
    required: true
  },

  loading: {
    type: Boolean,
    required: false
  }
});
</script>
Salin selepas log masuk
// file: App.vue
// ...
const loading = ref(false);

function loadRecords() {
  loading.value = true;

  axios
    .get('https://jsonplaceholder.typicode.com/posts')
    .then((response) => {
      records.value = response.data;
    })
    .catch((error) => {
      console.log(error);
    })
    .finally(() => {
      loading.value = false;
    });
}
// ...
Salin selepas log masuk
<!-- file: App.vue -->
<!-- ... -->
<PaginatedAutocomplete :items="records" :loading="loading" />
<!-- ... -->
Salin selepas log masuk

At this point, we have a basic list of a hundred records, but it’s not paginated and it doesn’t support searching. If you’re using Vuetify 2, the records won’t show up correctly - you will need to set the item-text prop to title. This is already the default value in Vuetify 3. Next, we will adjust the request parameters to attain the desired behavior. In a real project, the back-end would typically provide you with parameters such as page and search/query. Here, we have to get a little creative. We can define a pagination object on our end with page: 1, itemsPerPage: 10 and total: 100 as the default values. In a realistic scenario, you likely wouldn’t need to supply the first two for the initial request, and the third would only be received from the response. JSON Placeholder employs different parameters called _start and _limit. We can reshape our local data to fit this.

// file: App.vue
// ...
const pagination = ref({
  page: 1,
  perPage: 10,
  total: 100
});

function loadRecords() {
  loading.value = true;

  const params = {
    _start: (pagination.value.page - 1) * pagination.value.perPage,
    _limit: pagination.value.perPage
  };

  axios
    .get('https://jsonplaceholder.typicode.com/posts', { params })
    .then((response) => {
      records.value = response.data;
      pagination.value.total = response.headers['x-total-count'];
    })
    .catch((error) => {
      console.log(error);
    })
    .finally(() => {
      loading.value = false;
    });
}
// ...
Salin selepas log masuk

Up to this point, you might not have encountered any new concepts. Now we get to the fun part - detecting the end of the current list and triggering the request for the next page of records. Vuetify has a directive called v-intersect, which can inform you when a component you attached it to enters or leaves the visible area in your browser. Our interest lies in its isIntersecting return argument. The detailed description of what it does can be found in MDN Web Docs. In our case, it will allow us to detect when we’ve reached the bottom of the dropdown list. To implement this, we will attach the directive to our v-autocomplete‘s append-item slot.

To ensure we don’t send multiple requests simultaneously, we display the element only when there’s an intersection, more records are available, and no requests are ongoing. Additionally, we add the indicator to show that a request is currently in progress. This isn’t required, but it improves the user experience. Vuetify’s autocomplete already has a loading bar, but it might not be easily noticeable if your eyes are focused on the bottom of the list. We also need to update the response handler to concatenate records instead of replacing them, in case a page other than the first one was requested.

To handle the intersection, we check for the first (in Vuetify 2, the third) parameter (isIntersecting) and emit an event to the parent component. In the latter, we follow this up by sending a new request. We already have a method for loading records, but before calling it, we need to update the pagination object first. We can do this in a new method that encapsulates the old one. Once the last page is reached, we shouldn’t send any more requests, so a condition check for that should be added as well. With that implemented, we now have a functioning infinite scroll.

// file: PaginatedAutocomplete.vue
<template>
  <v-autocomplete
    :items="items"
    :loading="loading"
    :menu-props="{ maxWidth: 300 }"
    class="autocomplete"
    clearable
  >
    <template #append-item>
      <template v-if="!!items.length">
        <div v-if="!loading" v-intersect="handleIntersection" />

        <div v-else class="px-4 py-3 text-primary">Loading more...</div>
      </template>
    </template>
  </v-autocomplete>
</template>

<script setup>
defineProps({
  items: {
    type: Array,
    required: true
  },

  loading: {
    type: Boolean,
    required: false
  }
});

const emit = defineEmits(['intersect']);

function handleIntersection(isIntersecting) {
  if (isIntersecting) {
    emit('intersect');
  }
}
</script>
Salin selepas log masuk
// file: App.vue
// ...
function loadRecords() {
  loading.value = true;

  const params = {
    _start: (pagination.value.page - 1) * pagination.value.perPage,
    _limit: pagination.value.perPage
  };

  axios
    .get('https://jsonplaceholder.typicode.com/posts', { params })
    .then((response) => {
      if (pagination.value.page === 1) {
        records.value = response.data;
        pagination.value.total = response.headers['x-total-count'];
      } else {
        records.value = [...records.value, ...response.data];
      }
    })
    .catch((error) => {
      console.log(error);
    })
    .finally(() => {
      loading.value = false;
    });
}

function loadNextPage() {
  if (pagination.value.page * pagination.value.perPage >= pagination.value.total) {
    return;
  }

  pagination.value.page++;

  loadRecords();
}
// ...
Salin selepas log masuk

Efficiency Meets Precision: Moving Search to the Back-end

To implement server-side searching, we begin by disabling from-end filtering within the v-autocomplete by adjusting the appropriate prop value (no-filter). Then, we introduce a new property to manage the search string, and then bind it to v-model:search-input (search-input.sync in Vuetify 2). This differentiates it from the regular input. In the parent component, we capture the event, define a query property, update it when appropriate, and reset the pagination to its default value, since we will be requesting page one again. We also have to update our request parameters by adding q (as recognized by JSON Placeholder).

// file: PaginatedAutocomplete.vue
<template>
  <v-autocomplete
    :items="items"
    :loading="loading"
    :menu-props="{ maxWidth: 300 }"
    class="autocomplete"
    clearable
    no-filter
    v-model:search-input="search"
    @update:search="emitSearch"
  >
    <template #append-item>
      <template v-if="!!items.length">
        <div v-if="!loading" v-intersect="handleIntersection" />

        <div v-else class="px-4 py-3 text-primary">Loading more...</div>
      </template>
    </template>
  </v-autocomplete>
</template>

<script setup>
import { ref } from 'vue';

defineProps({
  items: {
    type: Array,
    required: true
  },

  loading: {
    type: Boolean,
    required: false
  }
});

const emit = defineEmits(['intersect', 'update:search-input']);

function handleIntersection(isIntersecting) {
  if (isIntersecting) {
    emit('intersect');
  }
}

const search = ref(null);

function emitSearch(value) {
  emit('update:search-input', value);
}
</script>
Salin selepas log masuk
// file: App.vue
<script>
// ...
const query = ref(null);

function handleSearchInput(value) {
  query.value = value;

  pagination.value = Object.assign({}, { page: 1, perPage: 10, total: 100 });

  loadRecords();
}

onMounted(() => {
  loadRecords();
});
</script>

<template>
  <main>
    <PaginatedAutocomplete
      :items="records"
      :loading="loading"
      @intersect="loadNextPage"
      @update:search-input="handleSearchInput"
    />
  </main>
</template>
Salin selepas log masuk
// file: App.vue
// ...
function loadRecords() {
  loading.value = true;

  const params = {
    _start: (pagination.value.page - 1) * pagination.value.perPage,
    _limit: pagination.value.perPage,
    q: query.value
  };
// ...
Salin selepas log masuk

If you try the search now and pay attention to the network tab in developer tools, you will notice that a new request is fired off with each keystroke. While our current dataset is small and loads quickly, this behavior is not suitable for real-world applications. Larger datasets can lead to slow loading times, and with multiple users performing searches simultaneously, the server could become overloaded. Fortunately, we have a solution in the Lodash library, which contains various useful JavaScript utilities. One of them is debouncing, which allows us to delay function calls by leaving us some time to call the same function again. That way, only the latest call within a specified time period will be triggered. A commonly used delay for this kind of functionality is 500 milliseconds. We can install Lodash by running the command npm install lodash. In the import, we only reference the part that we need instead of taking the whole library.

// file: PaginatedAutocomplete.vue
// ...
import debounce from 'lodash/debounce';
// ...
Salin selepas log masuk
// file: PaginatedAutocomplete.vue
// ...
const debouncedEmit = debounce((value) => {
  emit('update:search-input', value);
}, 500);

function emitSearch(value) {
  debouncedEmit(value);
}
// ...
Salin selepas log masuk

Now that’s much better! However, if you experiment with various searches and examine the results, you will find another issue - when the server performs the search, it takes into account not only post titles, but also their bodies and IDs. We don’t have options to change this through parameters, and we don’t have access to the back-end code to adjust that there either. Therefore, once again, we need to do some tweaking of our own code by filtering the response data. Note that in a real project, you would discuss this with your back-end colleagues. Loading unused data isn’t something you would ever want!

// file: App.vue
// ...
.then((response) => {
      const recordsToAdd = response.data.filter((post) => post.title.includes(params.q || ''));

      if (pagination.value.page === 1) {
        records.value = recordsToAdd;
        pagination.value.total = response.headers['x-total-count'];
      } else {
        records.value = [...records.value, ...recordsToAdd];
      }
    })
// ...
Salin selepas log masuk

To wrap up all the fundamental functionalities, we need to add record selection. This should already be familiar to you if you’ve worked with Vuetify before. The property selectedRecord is bound to model-value (or just value in Vuetify 2). We also need to emit an event on selection change, @update:model-value, (Vuetify 2: @input) to propagate the value to the parent component. This configuration allows us to utilize v-model for our custom component.

Because of how Vuetify’s autocomplete component works, both record selection and input events are triggered when a record is selected. Usually, this allows more customization options, but in our case it’s detrimental, as it sends an unnecessary request and replaces our list with a single record. We can solve this by checking for selected record and search query equality.

// file: App.vue
// ...
function handleSearchInput(value) {
  if (selectedRecord.value === value) {
    return;
  }

  query.value = value;

  pagination.value = Object.assign({}, { page: 1, perPage: 10, total: 100 });

  loadRecords();
}

const selectedRecord = ref(null);
// ...
Salin selepas log masuk
<!-- file: App.vue -->
<template>
  <main>
    <PaginatedAutocomplete
      v-model="selectedRecord"
      :items="records"
      :loading="loading"
      @intersect="loadNextPage"
      @update:search-input="handleSearchInput"
    />
  </main>
</template>
Salin selepas log masuk
<!-- file: PaginatedAutocomplete.vue -->
<!-- ... -->
  <v-autocomplete
    :items="items"
    :loading="loading"
    :menu-props="{ maxWidth: 300 }"
    :model-value="selectedItem"
    class="autocomplete"
    clearable
    no-filter
    v-model:search-input="search"
    @update:model-value="emitSelection"
    @update:search="emitSearch"
  >
<!-- ... -->
Salin selepas log masuk
// file: PaginatedAutocomplete.vue
// ...
const emit = defineEmits(['intersect', 'update:model-value', 'update:search-input']);

function handleIntersection(isIntersecting) {
  if (isIntersecting) {
    emit('intersect');
  }
}

const selectedItem = ref(null);

function emitSelection(value) {
  selectedItem.value = value;

  emit('update:model-value', value);
}
// ...
Salin selepas log masuk

Almost done, but if you are thorough with your testing, you will notice an annoying glitch - when you do a search, scroll down, then do another search, the dropdown scroll will remain in the same place, possibly causing a chain of new requests in quick succession. To solve this, we can reset the scroll position to the top whenever a new search input is entered. In Vuetify 2, we could do this by referencing the internal v-menu of v-autocomplete, but since that’s no longer the case in Vuetify 3, we need to get creative. Applying a unique class name to the menu allows us to select it through pure JavaScript and then follow up with necessary adjustments.

<!-- file: PaginatedAutocomplete.vue -->
<!-- ... -->
<v-autocomplete
  ...
  :menu-props="{ maxWidth: 300, class: `dropdown-${uid}` }"
  ...
>
<!-- ... -->
Salin selepas log masuk
// file: PaginatedAutocomplete.vue
// ...
const debouncedEmit = debounce((value) => {
  emit('update:search-input', value);

  resetDropdownScroll();
}, 500);

function emitSearch(value) {
  debouncedEmit(value);
}

const uid = Math.round(Math.random() * 10e4);

function resetDropdownScroll() {
  const menuWrapper = document.getElementsByClassName(`dropdown-${uid}`)[0];
  const menuList = menuWrapper?.firstElementChild?.firstElementChild;

  if (menuList) {
    menuList.scrollTop = 0;
  }
}
// ...
Salin selepas log masuk

There we have it, our custom autocomplete component with server side filtering and pagination is now complete! It was rather simple in the end, but I’m sure you would agree that the way to the solution was anything but with all these little tweaks and combinations we had to make.

If you need to compare anything with your work, you can access the source files through a GitHub repository here.

Aperçu et conclusion

Le voyage ne doit pas nécessairement s’arrêter là. Si vous avez besoin d'une personnalisation plus poussée, vous pouvez rechercher des idées dans la documentation Vuetify. Il existe d’innombrables possibilités à explorer. Par exemple, vous pouvez essayer de travailler avec plusieurs valeurs à la fois. Ceci est déjà pris en charge par Vuetify, mais peut nécessiter des ajustements supplémentaires pour être combiné avec nos solutions. Pourtant, c’est une chose utile à avoir dans de nombreux projets. Vous pouvez également essayer de personnaliser le modèle. Vous avez le pouvoir de redéfinir l’apparence de vos modèles de sélection, de vos modèles de liste, etc. Cela ouvre la porte à la création d'interfaces utilisateur qui s'alignent parfaitement avec la conception et l'image de marque de votre projet.

Il existe de nombreuses autres options en plus de celles-là. En fait, la profondeur de la personnalisation disponible justifie la création d’articles supplémentaires pour couvrir de manière exhaustive ces sujets avancés. En fin de compte, la pile Vue + Vuetify n'est pas la seule à prendre en charge quelque chose comme ça. Si vous travaillez avec d'autres frameworks, je vous encourage à essayer de développer vous-même un équivalent à celui-ci.

En conclusion, nous avons transformé un composant de base en une solution spécialisée qui correspond à nos besoins. Vous disposez désormais d'un outil polyvalent qui peut être appliqué à un large éventail de projets. Chaque fois que vous travaillez avec de longues listes d’enregistrements, une solution de pagination et de filtrage côté serveur devient votre stratégie de prédilection. Il optimise non seulement les performances du point de vue du serveur, mais garantit également une expérience de rendu plus fluide pour vos utilisateurs. Avec quelques ajustements, nous avons résolu certains problèmes courants et ouvert de nouvelles possibilités d'ajustements supplémentaires.

Atas ialah kandungan terperinci Cara menyesuaikan medan autolengkap/pilih untuk berfungsi dengan penapisan dan penomboran bahagian pelayan. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!