Can you force Vue.js to reload/re-render?
Trigger a Vue.js re-render by :key
attribute update on a component, effectively resetting the component:
To boostrap re-render, call reRender()
causing forceRenderKey
increment, making Vue discard the current instance and spawn a fresh one for <your-component>
.
Reactivity at your service
Vue.js orbits around a reactive system, which implies automatic updates when state changes occur. Before you usher in this.$forceUpdate()
, consider these solutions that stick to Vue's reactive principles:
- Computed Properties: They are cached and only recompute when their dependencies have changed. They provide a reactive method to forward the DOM updates in response to state changes.
- Watchers: When you need to respond to more complex data changes, Vue provides the
watch
option. It allows you to execute arbitrary logic when certain state changes occcur. - Vue.set() or vm.$set(): If you're dynamically adding new properties to an existing object, Vue can't track changes unless it's clued in using these methods.
:key to fresh start
Binding :key
to a variable reinitializes the component when the key value changes. However, be judicious when adjusting the key:
Tweak reactiveKey
only when you have changes that are not being automatically handled.
Reactive property handling
Ensure properties in data
are reactively declared. Keep in mind, Vue can't understand the changes if a property is added dynamically after component instantiation. Either declare reactively up front or use set
methods.
The router trick
In Single Page Applications (SPAs), full refresh of the route's components can be achieved using Vue Router's provided method:
Real-life scenarios
Non-reactive property updates
When you're adding properties to an object post creation, Vue struggles to track the changes. Bring in Vue.set()
or vm.$set()
:
Appropriate moments for ``$forceUpdate`
Consider using $forceUpdate
when:
- Evergreen APIs: When working with third-party libraries that perform non-Vue dollhouse renovations.
- Aftermaths of the Hulk: Because manual DOM manipulation can bypass Vue's reactivity.
Trivial ``$forceUpdate` usage
By hand $forceUpdate
usage can lead to dirty code and performance hits. Treat it as an indicator of reactivity issues rather than a cure.
Where to avoid
- Dependency updates: Your components should be able to sense and respond to changes from the store or props.
- Animation Galore: Controlling animations with
$forceUpdate
gives a bad performance and hard-to-maintain code. Instead, employ the Vue animations. - User Input: There are reactive solutions available when dealing with user input data.
Was this article helpful?