I have Vue instances which continually poll for some status, and I want to cancel the polling if the instance is destroyed.
Currently, I do the following logic, but curious if there's a built-in property or method to simplify this:
export default {
data: () => ({
destroyed: false // seems like an anti-pattern
}),
beforeDestroy(){
this.destroyed = true; // seems like an anti-pattern
},
methods: {
check(){
if (this.destroyed) return; // would prefer this.$isDestroyed
if (await forSomething()) {
return this.check();
}
}
},
mounted(){
this.check();
}
}
You can use the beforeDestroy hook to cancel the polling instead of adding a new data property.
export default { methods: { check(){ if (this._isBeingDestroyed) return; if (await forSomething()) { return this.check(); } } }, mounted(){ this.check(); }, beforeDestroy() { this._isBeingDestroyed = true; } }
Alternatively, you can use the isDestroyed computed property from the vue-composition-api package.
import { computed, onBeforeUnmount } from 'vue-composition-api'export default { computed: { isDestroyed: computed(() => this._isBeingDestroyed) }, methods: { check(){ if (this.isDestroyed) return; if (await forSomething()) { return this.check(); } } }, mounted(){ this.check(); }, setup() { onBeforeUnmount(() => { this._isBeingDestroyed = true }) } }