简体   繁体   中英

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>

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) {
      this.gridFilter.buttonflag = !newVal
    },
  },
}

demo

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM