Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to stop triggering vuejs watch methods when the value is changed by the method itself?

watch: {
        alert() {
          setTimeout(() => {
            this.alert = "";
          }, 4000);
        }
      }

Here, alert method is first triggered by the DOM and its triggered again when the value is changed by the method. is there any way to stop repeating?

My goal is here to check if the value of 'alert' is changed and if it's changed, I want to reset the value after 4s and also count how many times it was changed.

like image 650
Touha Avatar asked Jan 07 '19 17:01

Touha


People also ask

How do I watch data changes on Vue instance?

Using watchers in Vue # vue file we can watch for changes in data or props by using watch . For example, the below code will watch for a change in the data element pageData , and run a function according to the value it is changed to.

How does watch work in Vuejs?

The Vue. js Watcher or watch property allows the developers to listen to the component data and run whenever they change a particular property. The watcher or watch property is a unique Vue. js feature that lets you keep an eye on one property of the component state and run a function when that property value changes.

What is the difference between watch and computed in Vuejs?

Computed props can react to changes in multiple props, whereas watched props can only watch one at a time. Computed props are cached, so they only recalculate when things change. Watched props are executed every time.

What is the difference between computed and methods in Vue?

Computed Caching vs Methods For the end result, the two approaches are indeed exactly the same. However, the difference is that computed properties are cached based on their reactive dependencies. A computed property will only re-evaluate when some of its reactive dependencies have changed.


1 Answers

Following Roy J suggestion, try putting a change handler on the DOM instead of using a watcher.

new Vue({
  el: '#app',

  data() {
    return {
      alert: '',
      alertCounter: 0,

      resetTimeoutId: null,
      resetTimeoutDelay: 1000, // 4000
    }
  },

  methods: {
    reset() {
      this.incrementAlertCounter()
      this.handlePreviousResetTimeout()
      this.resetTimeoutId = setTimeout(() => {
        this.alert = ''
      }, this.resetTimeoutDelay)
    },

    handlePreviousResetTimeout() {
      if (!this.resetTimeoutId) return
      clearTimeout(this.resetTimeoutId)
    },

    incrementAlertCounter() {
      this.alertCounter += 1
    },
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input v-model="alert" type="text" @change="reset">
  <span>{{ alertCounter }}</span>
</div>
like image 118
Ricky Avatar answered Oct 01 '22 19:10

Ricky