Home > OS >  Vue.js Prevent watch trigger on load
Vue.js Prevent watch trigger on load

Time:07-22

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>

CodePudding user response:

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

CodePudding user response:

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.

  • Related