Open In App

How to Implement Debounce in Vue2 ?

Last Updated : 05 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Debouncing is a programming practice used to ensure that time-consuming tasks do not fire so often, making them more efficient. In the context of user input, debounce is particularly useful. For instance, when dealing with search input or scroll events, debounce helps delay the execution of a function until a certain amount of time has passed since the last invocation. In this article, we will explore how to implement debounce in Vue 2, enhancing the responsiveness of your applications.

Steps to create and configure the project

Step 1: Install Vue 2

Before diving into the implementation, make sure you have Vue 2 installed. You can install vue 2 using the below npm command.

npm install vue@2

Step 2: Create a Vue project

Create a Vue project and move that directory using the below commands.

vue create vue-debounced-count
cd vue-debounced-count

Step 3: Install Lodash Library

Debouncing is often implemented using the lodash library, which provides a debounce function. Install lodash using npm.

npm install lodash

Step 4: Create files inside src folder

Inside the components folder of the src folder create a “DynamicTable.vue” file that holds the main structure and UI logic.

Step 5: Create file to write debounce logic

Now, inside the src folder create a folder with name “utils”. Inside utils folder create a “debounce.js” file that holds the debouncing logic to implement it with vue 2.

Step 5: Run the App

Run the application using the below command.

npm run serve

Project Structure:
Screenshot-2024-01-03-165630

Example: The below code example will illustrate how you can implement debouncing in Vue2.

Javascript




<!-- src/App.vue -->
 
<template>
  <div id="app">
    <DynamicTable />
  </div>
</template>
 
<script>
import DynamicTable from './components/DynamicTable.vue';
 
export default {
  components: {
    DynamicTable,
  },
};
</script>
 
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>


Javascript




<!-- src/components/DynamicTable.vue file -->
 
<template>
<div class="dynamic-table">
  <h1>Beautiful Dynamic Table</h1>
  <div class="filter-inputs">
    <input v-model="filterName"
           @input="handleFilter"
           placeholder="Filter by Name" />
    <input v-model="filterEmail"
           @input="handleFilter"
           placeholder="Filter by Email" />
  </div>
 
  <table>
    <thead>
      <tr>
        <th>Name</th>
        <th>Email</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="user in filteredUsers" :key="user.id">
        <td>{{ user.name }}</td>
        <td>{{ user.email }}</td>
      </tr>
    </tbody>
  </table>
</div>
</template>
 
<script>
import { useDebounce } from '../utils/debounce';
 
export default {
data() {
  return {
    users: [
      { id: 1, name: 'John Doe', email: 'john@example.com' },
      { id: 2, name: 'Jane Smith', email: 'jane@example.com' },
      { id: 3, name: 'Bob Johnson', email: 'bob@example.com' },
      // Add more users as needed
    ],
    filterName: '',
    filterEmail: '',
    filteredUsers: [],
  };
},
methods: {
  handleFilter: useDebounce(function () {
    this.filterUsers();
  }, 300),
  filterUsers() {
    const filteredUsers = this.users.filter((user) => {
      const nameMatch =
              user.name.toLowerCase()
                .includes(this.filterName.toLowerCase());
      const emailMatch =
              user.email.toLowerCase()
                .includes(this.filterEmail.toLowerCase());
      return nameMatch && emailMatch;
    });
    this.filteredUsers = filteredUsers.length > 0 ?
        filteredUsers : this.users;
  },
},
created() {
  this.filteredUsers = this.users;
},
};
</script>
 
<style scoped>
.dynamic-table {
max-width: 800px;
margin: 50px auto;
text-align: center;
}
 
h1 {
font-size: 24px;
margin-bottom: 20px;
color: #3498db;
}
 
.filter-inputs {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
}
 
input {
width: 48%;
padding: 10px;
font-size: 16px;
border: 1px solid #ddd;
border-radius: 5px;
}
 
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
 
thead {
background-color: #3498db;
color: #fff;
}
 
th,
td {
padding: 12px;
border: 1px solid #ddd;
font-size: 14px;
}
 
th {
background-color: #2980b9;
}
 
tr {
transition: background-color 0.3s;
}
 
tr:hover {
background-color: #e0e0e0;
}
</style>


Javascript




<!-- src/utils/debounce.js file -->
 
export const useDebounce = function (func, delay = 300) {
  let timeoutId;
 
  return function (...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func.apply(this, args), delay);
  };
};


Output:

ezgifcom-video-to-gif-converter-(12)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads