Preventing Vue.js from triggering watch on initial load

I need to implement a feature where a button is initially disabled and only becomes enabled when the input value is changed. To achieve this, I am using a boolean flag that is set to true by default and turns false only when the input changes. The v-model of the input is linked to an Object property.

The issue arises when the page first loads because it triggers the watch function, causing the boolean value to be set to false. This results in the button never being disabled. How can I modify the code so that the watch function only triggers when the value changes?

Here is the modified code snippet:

class GridFilters {
  constructor(grid) {
    this.grid = grid;
    this.filterName = '';
    this.buttonflag = true;
    this.filterError = false;
  }
}

export default {
  data() {
    return {
      gridFilter: {},
    };
  },
  created() {
    this.gridFilter = new GridFilters(this); 
  },
  watch: {
    'gridFilter.filterName': function () {
      this.gridFilter.buttonflag = false;
    },
  },
};

HTML

<input placeholder="Enter a name" v-model="gridFilter.filterName" ref="filterName" @keydown="gridFilter.filterError=false" />
<button @click="save()" v-bind:disabled="gridFilter.buttonflag?true:false">Save Filter</button>

Answer №1

To address this issue, one approach is to handle the situation where the previous value is undefined. In the watch handler, the new value and old value are passed as arguments:

export default {
  watch: {
    'gridFilter.filterName': function (newVal, oldVal) {
      if (oldVal === undefined) {
        return
      }

      this.gridFilter.buttonflag = false
    },
  },
}

See demo 1 for reference.

Another option is to enhance the user experience by toggling the gridFilter.buttonflag to true when the new value of gridFilter.filterName is empty. This ensures that if the input is cleared, the button will be disabled again:

export default {
  watch: {
    'gridFilter.filterName': function (newVal) {
      this.gridFilter.buttonflag = !newVal
    },
  },
}

Explore demo 2 for a practical demonstration.

Answer №2

No need for the watcher in this case. Simply utilize the value of gridFilter.filterName directly on the button:

<button … :disabled=“gridFilter.filterName === ‘’”>

This way, if filterName is an empty string (as initialized), the button will be disabled.

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

Jquery plugin experiencing a malfunction

I am encountering an issue with my custom plugin as I am relatively new to this. My goal is to modify the properties of div elements on a webpage. Here is the JavaScript code I am using: (function($) { $.fn.changeDiv = function( options ) { var sett ...

The ultimate guide to loading multiple YAML files simultaneously in JavaScript

A Ruby script was created to split a large YAML file named travel.yaml, which includes a list of country keys and information, into individual files for each country. data = YAML.load(File.read('./src/constants/travel.yaml')) data.fetch('co ...

Retrieve the selected item from a Vuetify data table

I am trying to achieve a functionality with my v-data-table that includes Show-select. I need to be able to access the data of the items I have selected and ideally, I would like to display an alert with the value of the first column when an item is checke ...

Experiencing a console error which reads: "SyntaxError: Missing ) after argument list."

While working on configuring a new React CSR app and incorporating some boilerplate libraries, I encountered an error in the console: Uncaught SyntaxError: missing ) after argument list (at @emotion_react_macro.js?v=30f6ea37:29894:134) I am hesitant to ma ...

The URL is being modified, yet the page remains static in the React application

I've been working on setting up a router with react-router-dom, but I'm facing an issue where my URL gets updated without the page routing to the specified component. Here's a snippet from my App.js: import "./App.css"; import { Br ...

Keycloak does not support using the updateToken() function within an asynchronous function

In our development of a Spring application with React/Redux frontend, we faced an issue with Keycloak authentication service. The problem arose when the access token expired and caused unexpected behavior in our restMiddleware setup. Here is a simplified v ...

Retrieving hashtags from a text

If I had a string like this var feedback = "Yum! #yummy #delicious at #CZ" Is there an efficient way to extract all the hashtags from the string variable? I attempted using JavaScript's split() method, but it seems cumbersome as I have to repeate ...

The Ajax response fails to update my viewmodel

I have a value and a list that I need to update from within an Ajax callback. After retrieving a fresh value using .get(), I try to assign it to my view model's property, but the UI does not refresh properly. Below is the code snippet: function Searc ...

What is the significance of the -infinity value in the JavaScript console?

Recently, while learning JavaScript ES6, I came across a strange result of -infinity on my console when running the following code: let numeros = [1, 5, 10, 20, 100, 234]; let max = Math.max.apply(numeros); console.log(max); What does this ...

Is it considered acceptable to house a myriad of variables within the token object in NodeJS?

Currently working on implementing authentication with NodeJS, expressJS, mongodb and React Native. Is it acceptable to include multiple variables in the token object like shown in this example? const token = jwt.sign( { userId: user. ...

Using Python's Requests library to authenticate on a website using an AJAX JSON POST request

I'm a beginner in Python and struggling to create the correct code for using Python requests to log in to a website. Here is the form code from the website: <form autocomplete="off" class="js-loginFormModal"> <input type="hidden ...

How can I retrieve the value of a <span> element for a MySQL star rating system?

Source: GitHub Dobtco starrr JS plugin Implementing this plugin to allow users to evaluate a company in various categories and store the feedback in a MySQL database. Enhancement: I have customized the javascript file to enable the use of star ratings fo ...

Incorrectly resolving routes in the generate option of Nuxt JS's .env configuration file

Having trouble using Nuxt JS's 2.9.2 generate object to create dynamic pages as static files by referencing a URL from my .env file: nuxt.config.js require('dotenv').config(); import pkg from './package' import axios from 'a ...

The error message in Express points to module.js line 550 and states that the module cannot be

I am currently in the process of setting up a basic express application using the code below: const express = require('express'); const app = express() const bodyParser = require('body-parser'); const cookieParser = require('cooki ...

Keep the music playing by turning the page and using Amplitude.js to continue the song

I have implemented Amplitude.js to play dynamic songs using a server-side php script. My objective is to determine if a song is currently playing, and if so, before navigating away from the page, save the song's index and current position (in percenta ...

I keep encountering the error message "ReferenceError: window is not defined" in Next.js whenever I refresh the page with Agora imported. Can someone explain why this is happening?

Whenever I refresh my Next.js page with Agora SDK imported, I keep encountering the error "ReferenceError: window is not defined". It seems like the issue is related to the Agora import. I attempted to use next/dynamic for non-SSR imports but ended up with ...

I have a website hosted on Heroku and I am looking to add a blog feature to it. I initially experimented with Butter CMS, but I found it to be too pricey for my budget. Any suggestions on

I currently have a website running on Heroku with React on the front end and Node.Js on the back end. I want to incorporate a blog into the site, but after exploring ButterCMS, I found the pricing starting at $49 to be too steep for my budget. My goal is ...

Is it possible for me to move props object deconstruction into a separate module?

Here is my scenario: I have two React components that share 90% of the same props data, but display different HTML structures. I would like to avoid duplicating variable declarations in both component files. Is there a way to extract the common props des ...

Looking to crop a canvas without changing its dimensions using jQuery

I'm currently working on a project that involves overlaying two images; one uploaded by the user and the other a default image. However, I am facing an issue when the uploaded image is a rectangle instead of a square, causing the canvas to resize it. ...

"Dynamically moving" background on canvas

Struggling to animate a dynamic "background" for my canvas project using raphaelJS. Here's the code snippet I'm working with: function bg(){ h = 0; var terra = paper.rect(0, 500 + h, 900, 100); terra.attr({'fill': '# ...