The Invalidation Controller is a tiny class (less than 200 bytes gzipped) which enables you to manually force Vue computed properties to be re-evaluated. Its design is greatly inspired by the web API's AbortController
.
Nine out of ten times, you don't want to use this package. Manually invoking recomputations often violates the principle of unidirectional data flow.
However, since we don't live in a perfect world, there may be external entities in your application which are used as signaling devices rather than data sources.
That's what this package provides. It abstracts signals away, shielding you from creating reactive dummy counters that hold no valuable data and just increment for the sake of invalidating other properties.
npm install vue-invalidation-controller
This code is exclusively an example of how the InvalidationController
class works. Do not do silly things like this.
You may also try out this example on CodeSandbox.
const Vue = require('vue')
const InvalidationController = require('vue-invalidation-controller')
new Vue({
el: '#app',
data: {
// Instantiate the invalidation controller
// Note that the controller instance doesn't *need* to be assigned to a reactive property
// on the Vue instance. We just put it here because we want to access it in our template.
controller: new InvalidationController()
},
computed: {
time() {
// Mark the computed property as invalidatable
this.controller.useSignal()
return Date.now()
}
},
template: `
<div>
Time: {{ time }}<br>
<!-- Click the button to activate the invalidation signal: -->
<button @click="controller.invalidate">Invalidate</button>
</div>`
})
- Create an
InvalidationController
instance. - Call the
useSignal()
method inside a computed property definition to make it invalidatable. - Use the
invalidate()
method to re-evaluate all invalidatable computed properties.
-
A controller's
invalidate()
method can be invoked more than once. -
The same controller instance can be used in more than one computed property — and even across multiple components.
-
The
useSignal()
method works with Vue's built-in dependency tracking. That's to say that, if needed, you may invoke that method inside of anif
/else
branch to conditionally make a computed property invalidatable. -
Because it's just a plain old Vue instance, the Invalidation Controller works flawlessly with Vue 3's composition API:
const { computed } = require('vue') const InvalidationController = require('vue-invalidation-controller') // ... const controller = new InvalidationController() const time = computed(() => { controller.useSignal() return Date.now() })
- The
vue-recomputed
package targets the same use case with a very different API design.