Utilize debounce functionality for custom filtering in a Vuetify data table

I am looking to enhance my search functionality by implementing a debounce method that would pause the search action after each keystroke for 1 second. However, even after implementing it, the search still occurs with every keystroke instead of waiting for the specified delay. What can I do differently?

Template:

  <v-data-table
        :pagination.sync="pagination"
        :rows-per-page-items="[10, 25, 50, 100, 200, 250, 500]"
        :headers="headers"
        :items="rows"
        select-all
        :search="search"
        :custom-filter="_debounce(searchFilter, 1000)"
        v-model="selected"
      >

Function in vue file's script:

_debounce(fn: Function, delay: number) {
  debounce(fn, delay)
},

The core function (found in custom library):

export const debounce = function (fn: Function, delay: number) {
  var timeoutID: any = null
  return function () {
    clearTimeout(timeoutID)
    timeoutID = setTimeout(function () {
      fn()
    }, delay)
  }
}

Answer №1

In my Vuetify project, I implement the custom-filter function along with lodash.debounce. Using customFilter allows me to search nested values by flattening when a column contains an Object. Additionally, I utilize a computed get/set method to handle the debounce.

// Interested in the v1.5 template?
// Check it out: https://codepen.io/pen?template=GVoaNe


// import debounce from 'lodash.debounce'

const App = {
  template: '#app-template',
  data: () => ({
    headers: [
      { text: 'Name', value: 'name' },
      { text: 'Age', value: 'age' },
      { text: 'Occupation', value: 'occupation' },
      { text: 'Hire Date', value: 'hide_date' },
      { text: 'Favorite Foods', value: 'foods' }
    ],
    items: [
      { name: 'John', age: 21, occupation: 'Temp', hide_date: '2022-12-01', foods: [{ type: 'breakfast', food: 'Eggs' }, { type: 'lunch', food: 'Sandwich' }, { type: 'dinner', food: 'Steak' }] },
	  // more items...
    ],
    search_value: ''
  }),
  computed: {
    // Adding debounce into a computed setter
    search: {
      get () { return this.search_value },
      set: debounce(function (value) {
        this.search_value = value 
      }, 300)
    }
  },
  methods: {
    /******************************
    * The custom filter function enables searching of nested properties by flattening nested values.
    * For instance, in this data example, the `foods` column has an array of objects that need to be flattened before performing a case-insensitive search.
    ******************************/
    customFilter (value, search, item) {
      return Object
        .values(item)
        .flat()
        .map(x => { return (!!x && typeof x === 'object') ? Object.values(x) : x })
        .flat()
        .some(x => x && x.toString().toLowerCase().includes(search.toLowerCase()))
    }
  }
}


new Vue({
  vuetify: new Vuetify(),
  render: h => h(App)
}).$mount('#app')
<link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="35535a5b4175001b4d">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="74020111001d120d34465a0c">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9fe9eafadfadb1e7">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9afacbcadb0bfa099ebf7a1">[email protected]</a>/dist/vuetify.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f69a999297859ed89293949983989593b6c2d8c6d8ce">[email protected]</a>/index.js"></script>

<script type="text/x-template" id="app-template">
  <v-app>
    <v-container>
      <v-data-table :headers="headers" :items="items" :search="search" :custom-filter="customFilter">
        <template #['item.foods']="{ item }">
          <pre>{{ item.foods }}</pre>
        </template>
        <template #top>
          <!-- Utilizing @input event for `debounceInput`, setting value of `search` (debounced 250ms) -->
          <v-text-field
            v-model="search"
            label="Search"
            outlined
            prepend-inner-icon="mdi-magnify"
            clearable
          />
        </template>
      </v-data-table>
    </v-container>
  </v-app>
</script>

<div id="app"></div>

Explore More Here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dropdown Menu with Bootstrap 4 Toggle Checkbox

Within a Bootstrap 4 dropdown menu, I integrated a checkbox styled with the Bootstrap Toggle Plugin. However, upon clicking the toggle switch, the menu abruptly closes. To address this issue, I added onclick="event.stopPropagation();" to the menu item, as ...

Why doesn't the style show up when JavaScript is turned off with Material UI, CSS Modules, and Next.js?

This is my first time diving into Material UI, CSS Modules, and Next.js with a project. Issue: I noticed that when I disable JavaScript in the Chrome DevTools, the styles are not being applied. I'm not sure if this has something to do with Materia ...

Unique Tags and Javascript: A customized approach

In the process of developing a web application, I am aiming for high standardization. To achieve this goal, I plan to utilize custom namespace tags that will be modified by JavaScript based on their functionality. For instance: <script type="text/java ...

"Is it possible to selectively load only a few images on a website that contains numerous

My website displays numerous images hosted on a server. Each page contains a maximum of 100 images, each within its own div element. At any given moment, only one div is visible due to the CSS "display" property, while the others are hidden using display:n ...

The alert box for model validation summary errors is deactivated when hidden using .hide() method

In my MVC web application form, there is an optional postcode finder. If there is no match for the entered postcode, I add a custom error message to the .validation-summary-errors section. After the error is fixed, I remove all instances of the postcode cl ...

Problem with sidebar animation: Functioning properly when open, but closes abruptly without animation in React using Tailwind CSS

When interacting with my Menu react component by clicking on the 'hamburger' icon that I created manually, the sidebar menu opens smoothly with an animation. However, the issue arises when trying to close the sidebar as it vanishes instantly with ...

Do these two JavaScript statements behave the same under the principles of functional programming in a React environment?

Is there a rule in functional programming that states these two approaches are equivalent? When working on a React application, I initially passed a function as an attribute using the second version where the first parameter is also passed. Out of curiosi ...

Modify the CSS class dynamically by clicking a button (using class names stored in an array)

How can I dynamically change a CSS class on button press while using an array of class names? When I hard code the classes in a switch statement, everything works fine. However, when trying to pull class names from an array, it jumps to the end of the swit ...

JavaScript - All values stored from the for loop are registering as undefined

Recently delving into the realm of JavaScript programming, I find myself faced with a new challenge. While not my first language, this is one of my initial ventures with it. My current project involves creating a chess program utilizing the HTML5 canvas fe ...

Bluebird refuses to execute the then() function, despite the code that was functional before

I am in the process of constructing a node framework for my upcoming projects, with a focus on easy management. The framework already includes a configuration module. Recently, I implemented an error handler and made updates to the Config module to incorp ...

Using multiple GET methods on a single route in Express and Sequelize can lead to conflicts

I've created a simple product CRUD application with routes to search for products by ID and by name. However, when I send a request to http://localhost:4000/products?name=pen, the routes conflict with each other and I'm unable to retrieve the pro ...

Sparse planeBufferGeometry in THREE.js is a specialized type of geometry that

I am currently working with a file that contains sparse elevation data derived from GPS information. I have been utilizing this data to fill a PlaneBuffer array with elevations. var vertices = new Float32Array( (grid.NCOL*grid.NROW) * 4 ); for (var i = 0, ...

Encountering a Cross-Origin Resource Sharing (CORS) error when attempting to process payments using Node.js

I am trying to process a payment using PayPal SDK. My frontend is built with AngularJS and my backend uses Node.js. In my frontend, I simply make a call to a route on my Node server like this: $http.post('/paypal/pay', cart) I have CORS config ...

Displaying random divs and subsequently animating them downwards using JavaScript

I am in the process of creating a random appearing div that then falls down. Here is the code I have so far: $(document).ready(function(){ $('#test').animate({top: 80 + '%'},900); }); <div id="test" style="background:#98bf21;heigh ...

Vue failing to render content from data object

I recently started using NuxtJs and decided to create a new file named test.vue within the pages directory. Below is the code snippet from my test.vue file: <template> <div> <h1 style="font-size: 30px">{{ message }} </h1> ...

Invalid sequencing of Nest.js async onModuleInit causing issues

I am dealing with a scenario where ServiceA relies on RedisService. In order for ServiceA to be fully operational, it must wait for RedisService to complete its initialization process (specifically, for RedisService.onModuleInit to be called and awaited). ...

Replicate the preceding input data by simply clicking a button

Here is some HTML and jQuery code that I am working with: $(".btn-copy").click(function() { var previousContent = $(this).prev()[0]; previousContent.select(); document.execCommand('copy'); }); <script src="https://cdnjs.cloudflare.com ...

Utilizing Captcha with Meteor's accounts-ui-bootstrap-3 for enhanced security

Is it possible to incorporate Captcha verification when utilizing the combo of Meteor packages accounts-ui-bootstrap-3 and accounts-password? What is the process for integrating a package such as captchagen with accounts-ui? ...

Identifying sluggish GPU performance on a mobile device using three.js: A guide for developers

My game runs extremely slow on older mobile devices like the Samsung Galaxy S4 and iPhone 5 when shadows are enabled. However, when shadows are turned off, performance improves significantly. Is there a way to detect a slow GPU in order to disable sh ...

Determine the current whereabouts and actions of the specified user

I am in the process of developing a command for my Discord JS bot that, when activated, will fetch the current game (or status if no game) of the user mentioned in the command. Subsequently, the bot will send a message stating Mentioned User has been playi ...