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.
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.
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With