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

Viewed 6297
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.

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>

Related