programing

메서드 자체에 의해 값이 변경되었을 때 vuejs 워치 메서드의 트리거를 정지할 수 있는 방법이 있습니까?

shortcode 2022. 7. 16. 14:59
반응형

메서드 자체에 의해 값이 변경되었을 때 vuejs 워치 메서드의 트리거를 정지할 수 있는 방법이 있습니까?

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

여기서 경보 메서드는 처음에 DOM에 의해 트리거되고 값이 메서드에 의해 변경되면 다시 트리거됩니다.반복을 멈출 방법은 없을까?

제 목표는 '경보' 값이 변경되었는지 확인하고 변경되면 4초 후에 값을 재설정하고 변경 횟수를 세는 것입니다.

Roy J의 제안에 따라, Roy J를 사용해보세요.change워처를 사용하는 대신 DOM 상의 핸들러를 사용합니다.

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>

언급URL : https://stackoverflow.com/questions/54079175/is-there-any-way-to-stop-triggering-vuejs-watch-methods-when-the-value-is-change

반응형