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

Rails 4 application encountering issues with rendering views when making a $.ajax request

I am a beginner in Rails and I am in the process of sending model data to a controller method from JavaScript for rendering a list of results... function submitResults() { resultURL = "/result"; resultData = JSON.stringify(results); $.ajax({ typ ...

Struggling with D3.js Angular CLI where Scope disappears within the tick() function?

Hey everyone, I'm currently in the process of incorporating a D3 visualization network graph into an Angular CLI project (http://bl.ocks.org/mbostock/1153292) using the ng2-nvd3 component. Here's the Angular component: import { Component, OnIn ...

Guide on setting up a Quasar Framework boot file for integrating vueI18n@next using the Vue Composition API

We are currently working on installing the latest vueI18n@next package in Quasar Framework to be used with Vue 2 and the Vue Composition API. The documentation for Vue I18n provides the following code snippet: import { createApp } from 'vue' impo ...

What is the reason for this basic callback running before the setTimeout function?

Interesting behavior is observed in this code, where 'output 2' is logged before 'output 1' due to the setTimeout function. const func1 = () => { setTimeout(() => { console.log('output 1'); }, 3000); }; con ...

Ways to modify an object similar to manipulating an array collection

Hey there, I've heard that iterating and editing objects (not arrays) is not the best practice. Is there a more efficient way to do it as easily as it can be done with an array of objects? Check out this link for reference new Vue({ el: '#app ...

As soon as I hit the submit button on my website form, the URL is automatically refreshed with the information I provided

I am a beginner when it comes to forms and recently copied and pasted this login snippet code: <div class="login-form-1"> <form id="login-form" class="text-left"> <div class="main-login-form"> <div class="login-group"> ...

Cross-origin resource sharing working smoothly on Chrome but facing issues on Safari and Firefox

When using my app, logging in works fine on Chrome, but I encounter issues on Safari and Firefox. On Safari, the error message is displayed as seen here: and on Firefox, the error message is displayed as seen here: However, everything functions correctl ...

Issue with Vue.js app display within Chrome extension

I have encountered an issue while trying to run a Vuejs app in a Chrome extension as a new tab. The app renders perfectly fine when running it from the dist/ folder using simplehttpserver dist/. However, when I attempt to load the dist folder as a Chrome E ...

Unlock the potential of Vuejs with parent collapse functionality

I am facing an issue where I have a child component with a <b-collapse> element, and I am trying to toggle its visibility from the parent component. While I have $bvModal for handling models, I couldn't find anything similar for collapses. Pare ...

Display the personalized list of user items on the MERN dashboard

I'm currently developing a React booking platform that interacts with my backend through a Rest API using axios and redux. My challenge now is to display personalized reservations and rooms for each user on the website. However, I'm facing an iss ...

What is the relationship between $.when, apply(), and $.done() within the scope of this function?

I recently received this function from a helpful SO user that allows for returning a variable number of jQuery $.get() requests. The initial part seems pretty straightforward, but I am struggling to understand how $.when(), apply(), and $.done() are inte ...

What is the method to invoke a function within another function in Angular 9?

Illustration ` function1(){ ------- main function execution function2(){ ------child function execution } } ` I must invoke function2 in TypeScript ...

Inject the ng-repeat variable into a personalized directive

When working with an ng-repeat and a custom directive, I am facing the challenge of passing the "item" variable from ng-repeat to the directive. Here is an example code snippet illustrating this situation: <li ng-repeat="item in list"> <div c ...

Tips for preventing duplicate properties in Material UI when using React JS

Incorporating components from Material-UI, I have designed a form where the state of inputs is controlled by the parent component. However, I encountered an error stating "No duplicate props allowed" due to having multiple onChange parameters. Is there a w ...

What is the best way to link to this list of options?

#episode-list { padding: 1em; margin: 1em auto; border-top: 5px solid #69c773; box-shadow: 0 2px 10px rgba(0,0,0,.8) } input { width: 100%; padding: .5em; font-size: 1.2em; border-radius: 3px; border: 1px solid #d9d9d9 } <div id="epis ...

An existing INPUT value can be modified by dynamically adding or subtracting values from SELECT OPTION

I currently have an <input readonly> field that displays the total_price value retrieved from a shopping cart stored in the database table. Moreover, I have included a <select> element with different transport options that can either increase o ...

Exploring the Power of NPM Modules in an Electron Renderer

Having trouble accessing lodash in an electron renderer. I'm a beginner with Electron and know that both the main process and renderer (local html file) have access to node. I can require something from node core like fs and it works fine, but when I ...

Reveal or conceal information with a dropdown menu feature

I am attempting to implement a feature where the image file upload section is hidden or displayed based on the selection made in a dropdown list. If the user selects option "2", the image upload section should be hidden. Conversely, if they choose option " ...

Discovering the type in Typescript by specifying a function parameter to an Interface

Consider this sample interface: interface MyInterface { x: AnotherThing; y: AnotherThingElse; } Suppose we make the following call: const obj: MyInterface = { x: {...}, y: {...}, } const fetchValue = (property: keyof MyInterface) => { ...

Achieving full child div coverage within a bordered parent div on Chrome

I am encountering an issue where I am trying to insert an image into a bordered div, but in Chrome 96.0 there are unexpected margins appearing from the top and left that I cannot seem to remove. Below is the code I am using: .wrapper { width: 36px; ...