Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

203
Views
Vue.js + Prevent watch trigger on load

I want to disable a button by default and enable it only when input value is changed.

So i am using a boolean flag which is true by default and is set to false only when input changes The input v-model is tied to an Object property.

The problem is when the page loads for the first time, it triggers the watch property and boolean value is set to false. hence the button is never disabled.How i can make the watch to trigger only when the value is changed?

Below is the code -

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>
about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

One solution is to ignore the change if the previous value is undefined. The watch handler receives the new value and old value as its first and second argument, respectively:

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

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

demo 1

Alternatively, you could improve the UX by setting gridFilter.buttonflag to true when the new value of gridFilter.filterName is empty. That way, if the user decides to clear the input, the button gets disabled again:

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

demo 2

about 4 years ago · Santiago Gelvez Report

0

You don’t need that watcher at all, I think. You can use the value of gridFilter.filterName directly on the button, like:

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

So if filterName is an empty string, as you set it initially, the button will be disabled.

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!