Can you force Vue.js to reload/re-render?
Just a quick question.
Can you force Vue.js
to reload/recalculate everything? If so, how?
Solution 1:
Try this magic spell:
vm.$forceUpdate();
No need to create any hanging vars :)
Update: I found this solution when I only started working with VueJS. However further exploration proved this approach as a crutch. As far as I recall, in a while I got rid of it simply putting all the properties that failed to refresh automatically (mostly nested ones) into computed properties.
More info here: https://vuejs.org/v2/guide/computed.html
Solution 2:
This seems like a pretty clean solution from matthiasg on this issue:
you can also use
:key="someVariableUnderYourControl"
and change the key when you want to component to be completely rebuilt
For my use case, I was feeding a Vuex getter into a component as a prop. Somehow Vuex would fetch the data but the reactivity wouldn't reliably kick in to rerender the component. In my case, setting the component key
to some attribute on the prop guaranteed a refresh when the getters (and the attribute) finally resolved.
Solution 3:
Please read this http://michaelnthiessen.com/force-re-render/
The horrible way: reloading the entire page
The terrible way: using the v-if hack
The better way: using Vue’s built-in forceUpdate method
The best way: key-changing on your component
<template>
<component-to-re-render :key="componentKey" />
</template>
<script>
export default {
data() {
return {
componentKey: 0,
};
},
methods: {
forceRerender() {
this.componentKey += 1;
}
}
}
</script>
I also use watch: in some situations.