How can I prevent vuejs watch methods from being triggered when the value is modified by the same method?

monitorChanges: {
        observeValue() {
          setTimeout(() => {
            this.observeValue = "";
          }, 4000);
        }
      }

In this scenario, the observeValue function is initially invoked by the DOM, but it repeats when the value is modified by the function. Is there a way to prevent this repetitive behavior?

The objective here is to monitor any changes in the 'observeValue' and reset the value after 4 seconds if it has been altered, while also keeping track of how many times it has been modified.

Answer №1

Upon Roy J's recommendation, consider implementing a change handler on the DOM rather than relying on a watcher.

new Vue({
  el: '#app',

  data() {
    return {
      alert: '',
      alertCounter: 0,

      resetTimeoutId: null,
      resetTimeoutDelay: 1000, // 4000
    }
  },

  methods: {
    reset() {
      this.incrementAlertCounter()
      this.handlePreviousResetTimeout()
      this.resetTimeoutId = setTimeout(() => {
        this.alert = ''
      }, this.resetTimeoutDelay)
    },

    handlePreviousResetTimeout() {
      if (!this.resetTimeoutId) return
      clearTimeout(this.resetTimeoutId)
    },

    incrementAlertCounter() {
      this.alertCounter += 1
    },
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input v-model="alert" type="text" @change="reset">
  <span>{{ alertCounter }}</span>
</div>

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

Can you provide an alternative code to access an element with the id of 'something' using vanilla JavaScript instead of jQuery's $('#something') syntax

Why am I seeing different console output for $('#list') and document.getElementById("list")? Here is the console printout: console.log($('#list')); console.log(document.getElementById("list")); However, the actual output in the cons ...

What could be causing the 500 response code when making a request to the NextJS API route within the app directory?

Every time I attempt to access my API route, a 500 Internal Server Error code is returned The origin of the request export const fetchSuggestion = async () => { const response = await fetch('/api/getSuggestion', { cache: 'no-store&ap ...

Firefoxx unable to communicate with server through ajax requests

My dilemma involves transmitting data to my server using the json data type with ajax. Oddly enough, in Firefox the server fails to receive any data at all, while in Chrome and IE the data is successfully transmitted and displayed on the server console. H ...

AngularJS directive that allows for either a click action to be passed or a ui-router state change to

I have a button (an a tag) that is displayed in multiple locations on my website. It is labeled "View Demo", and sometimes it directs to a demo page using an ui-sref: <a class="btn btn-primary" ui-sref="hamburger-push" target="_blank"> View Demo ...

Responsive text area with Django and Bootstrap

I created a small JavaScript script to ensure that a text area adjusts responsively based on the size of the accompanying image. It generally works well, but there is a strange random bug that I can't quite figure out. This is how the page should be d ...

In Vue.js, utilize a contenteditable div to dynamically add an HTML element and bind it with v-model

Below is the HTML code I have written. <div id="app"> <button @click="renderHtml">Click to append html</button> <div class="flex"> <div class="message" @input="fakeVmodel" v-html="html" contenteditable="true">< ...

Utilizing a TypeScript definition file (.d.ts) for typings in JavaScript code does not provide alerts for errors regarding primitive types

In my JavaScript component, I have a simple exporting statement: ./component/index.js : export const t = 'string value'; This component also has a TypeScript definition file: ./component/index.d.ts : export const t: number; A very basic Typ ...

Tips for providing arguments in the command line to execute a yarn script

Just starting out with JavaScript. I understand that npm allows for passing variables in the command line using process.env.npm_config_key like this: npm run --key="My Secret Passphrase" test:integration How can I achieve the same thing with yarn? I&apo ...

AngularJS Table Checkbox Selection Helper Functions

I am feeling completely lost and could really use some assistance. I have been looking at different examples but nothing seems to be helping me out. I have created a dynamic table with checkboxes. Whenever a row is selected, its id gets added to an array ...

Filtering rows in JQgrid is made easy after the addition of a new record

Here's the situation I'm facing: Every second, my script adds a new record using the "setInterval" function: $("#grid").jqGrid('addRowData', id, data, 'first').trigger("reloadGrid"); However, when users apply filters while t ...

The feature to hide columns in Vue-tables-2 seems to be malfunctioning

The issue I'm facing is with the hiddenColumns option not working as expected. Even when I set it to hiddenColumns:['name'], the name column remains visible. I've updated to the latest version, but the problem persists. UPDATE I am tr ...

The functionality of the MVC jQuery grid is currently malfunctioning

Recently, I attempted to integrate a jQuery grid plugin from gijgo.com into my MVC application. Following the instructions provided on c-sharpcorner and/or codeproject meticulously, however, upon running the application, I encountered a troubling JavaScrip ...

"I am encountering an issue where I am using React and Express to retrieve data from a database, and although I am able to return an array of

I am working on a React app that communicates with an API using Express. Currently, I am using the GET method to fetch data from a database, and my fetching code looks like this: const posts = []; fetch(URL) .then(response => response.json()) .then(jso ...

What causes a never-ending loading cycle on a website when a 404 error occurs?

My Express.js/Node.js website is hosted on Heroku. I am facing an issue where the server does not properly send a 404 error when a file cannot be found. Instead, the page keeps loading endlessly. How can I make the server stop loading when it encounters a ...

Guide on Redirecting in Express.js

I am seeking assistance with finding solutions. In short, I have created this API () with username: test and token: test. If the current date is past the meeting time, then open the meeting URL in a new tab. This check should occur every second. ...

Swap out the image backdrop by utilizing the forward and backward buttons

I am currently working on developing a Character Selection feature for Airconsole. I had the idea of implementing this using a Jquery method similar to a Gallery. In order to achieve this, I require a previous button, a next button, and the character disp ...

Using jQuery, adjust the width of child elements within a container by applying dynamic CSS styling

I am attempting to dynamically set the width of several child elements using jQuery. Here is what I am trying to achieve: Obtain the count of the desired containers (since there will be multiple instances of the .steps-container class in the DOM) Iterate ...

The feature of option display is not supported on Safari browser

I am facing an issue with the functionality of two dropdown menus. The options in the second dropdown are supposed to be shown based on the selection made in the first dropdown. While this feature works perfectly in Chrome, it seems to be malfunctioning i ...

Utilizing multiple applications concurrently in ExpressJS

Currently, I have iisnode up and running on IIS7 with a single app (app.js) that utilizes MongoDB. What I'm interested in is the ability to host multiple Express apps from the same location. For example, if someone were to navigate to /app2/, I want i ...

Revamp List Model through Ajax Integration in ASP .NET MVC5

Could someone please provide a hint on how to update the Model list in the view page after calling the Action Result with an Ajax request? Specifically, how can I refresh the current list model with the result of the Ajax call back? Here is the code for m ...