Utilizing Lodash debounce in VueJs watch feature while incorporating Typescript

When working with VueJS in Javascript, I can achieve the following:

import debounce from "lodash/debounce";

...

watch: {
  variable: debounce(function() {
    console.log('wow');
  }, 500)
}

However, when attempting to do the same in VueJS using Typescript, I encountered some issues:

npm i lodash-es
npm i @types/lodash-es -D

Within the component:

import { Component, Vue, Watch } from "vue-property-decorator";
import debounce from "lodash-es/debounce";

...

@Watch("variable")
debounce(function() {
  console.log('wow');
}, 500)

Unfortunately, errors occurred:

  • The 'debounce' function lacks a return type annotation and implicitly returns 'any'.
  • The number '500' is implicitly assigned with the type 'any'.

P.S. The following method worked without any issues:

func = debounce(() => {
    console.log('wow');
}, 500)

Answer №1

@Watch("variable")
debounce(function() {
  console.log('wow');
}, 500)

The given code does not have the correct syntax. A decorator should be applied to a class member with a specified name.

Using Lodash's debounce function with the Watch decorator is not straightforward, as the latter is intended for use with prototype methods.

One way to achieve this is by creating a custom decorator and chaining them, but this might lead to unwanted behavior due to the shared debounce interval across all component instances:

function Debounce(delay: number) {
  return (target: any, prop: string) => {
    return {
        configurable: true,
        enumerable: false,
        value: debounce(target[prop], delay)
    };
  }
}

...
@Watch('variable')
@Debounce(500)
onVariable() { ... }
...

A better approach would be to debounce an instance method, following the suggestions in the Vue.js documentation:

...
created() {
  this.onDebouncedVariable = debounce(this.onDebouncedVariable, 1000);
}

@Watch('count')
onVariable() {
    this.onDebouncedVariable();
}

onDebouncedVariable() { ... }
...

Answer №2

If you're looking for a solution, check out this link: https://www.npmjs.com/package/vue-debounce-decorator

Follow these steps once you have it:

  @Watch('value')
  @Debounce(300)
  private onValueChanged (val: string): void {
    // implement your code 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

I am currently having issues with the mustache syntax in vuejs, as it is not functioning properly

Having an issue with Vue.js where the mustache syntax isn't working properly. <!DOCTYPE html> <html> <head> <title>index</title> <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cg ...

When executing prisma generate, an error of TypeError is thrown stating that the collection is

While using typescript with Prisma, I encountered an issue when trying to run prisma generate, as it kept throwing the following error: TypeError: collection is not iterable. at keyBy (/node_modules/@prisma/client/generator-build/index.js:57685:21) at ...

Issue with submitting VueJS form on mobile devices, works fine on web browsers but not on

I have encountered a similar problem before, but I haven't found a suitable solution yet. In my VueJS application, the submit function works perfectly fine on desktop browsers like Chrome and Firefox, but for some reason it refuses to submit on mobil ...

Is it possible to efficiently structure intricate JSON data onto interfaces in TypeScript with the incorporation of observables?

I am currently working on creating a simple web news reader that relies heavily on the Google News API (). I have set up all the necessary services, models, etc. However, I am having difficulty mapping the data onto specific interfaces. The Google API retu ...

Having trouble with adding a listener or making @click work in VueJS?

Apologies for my limited experience with Vue. I am currently facing an issue where one of my click functions is not working as expected for multiple elements. The click event is properly triggered for the #app-icon element. However, the function is not be ...

What is the best way to transpile TypeScript within the Astro framework?

Recently, I decided to dive into exploring Astro for a couple of upcoming projects. In my research, I delved into the script and typescript sections of the documentation (), as well as (). However, I found the workflow somewhat counterintuitive and struggl ...

React's Redux persist is causing a duplication of requests being sent

I am currently utilizing redux-persist along with Redux Toolkit. I have observed a peculiar behavior where, upon changing the slice (RTK), a request is sent to the server. When using redux-persist without a persister, only one request is made as expected. ...

Navigating the world of getElementById and addEventListener outside of the DOM

Having some dynamic HTML code in my JS, I'm hoping to assign an ID to a particular tag: content: ` <p id="openKeyboard"> If the click happens, I want to trigger an event. </p> ` However, upon ...

Utilizing a string variable as a property name for dynamic typing

I am looking to dynamically create a type with a property name based on specified parameters. Although I can successfully create the object, I am facing challenges when trying to create the actual type. This dynamic type creation is essential for compositi ...

When compiling in Visual Studio 2019, the process terminated with exit code -1073741819

Today, upon returning to my asp .net core-project with react and typescript as front end, I encountered an error message after running the "Build" command. Can anyone shed some light on what this error means and how it can be fixed? Severity Code De ...

The pathway specified is untraceable by the gulp system

Hey there, I've encountered an issue with my project that uses gulp. The gulpfile.js suddenly stopped working without any changes made to it. The output I'm getting is: cmd.exe /c gulp --tasks-simple The system cannot find the path specified. ...

The value of 'Boolean' cannot be changed as it is a constant or a read-only property and cannot be assigned

I've been working on creating a TypeScript object to handle read/write permissions in my application, but I'm stuck on an issue with variable assignment that doesn't make sense to me. Any help or guidance would be greatly appreciated. expor ...

quickest method for retrieving a property by name, regardless of its location within the object hierarchy

I am looking for a solution to retrieve the value of a property from an object graph, and I am wondering if there is a more efficient alternative to the method I have outlined below. Instead of using recursion, I have chosen tree traversal because it cons ...

Lodash will return a false value when checking an empty object

I am working with the object req.user.stripe, which currently has a value of an empty object {}. I want to determine whether this object is empty or not by using the lodash function isEmpty(). However, when I use console.log(_.isEmpty(req.user.stripe)), it ...

Vue.js components are not being utilized within Laravel's blade files

I have integrated Vue.js with Node modules for a Laravel 5.4 project, but the components are not being displayed after running npm run watch. Even after installing npm and adding Vue.js file example in app.js, running npm run watch does not show any resul ...

Receiving undefined values when passing down props from an asynchronous API call

After diving into single file components in Vue in an effort to increase modularity, I've encountered issues with passing down props when they are set by an async response from an API. Currently, my project involves: parent component child comp ...

Tips for updating the input name in Vue.js

I need assistance with implementing a dynamic form where input names must be in array format and the array number should increase automatically for posting purposes. Here is my code snippet: <!doctype html> <html lang="{{ str_replace('_&apo ...

The Laravel and Vue.js axios delete function operates smoothly without displaying any errors, yet it fails to delete

I've implemented a web route to delete a contact by its specific id. Here's how it looks: Route::delete('/api/deleteContact/{id}', 'ContactController@destroy'); In my controller, I have the following method: public function ...

Error in AngularJS and TypeScript: Property 'module' is undefined and cannot be read

I'm attempting to incorporate TypeScript into my AngularJS 1.x application. Currently, my application utilizes Webpack as a module loader. I configured it to handle the TypeScript compilation by renaming all *.js source files to *.ts, and managed to ...

Tips for validating dates in Angular 4

Recently, I have started working with Angular and in my application I am facing a challenge regarding date validation. I need to validate a date input and display an error message based on the validation criteria. To achieve this, I am utilizing ngx-boots ...