How to rerender a component in Vuejs

The rerender of a component in vuejs is like refreshing the DOM again.It is because sometimes the element will not bind to the component.So in that case vue has provided $forceUpdate property inorder to refresh the DOM.

Scenario:- During binding of any list from one component to another component,the binding will not work sometimes.So it may be due to component does not refresh correctly.In this situation we can use forceupdate() to rerender the component again , so that binding gets refreshed in parent page. There are multiple solutions available to refresh the component.Here is the command to force refresh the component.

                this.$forceUpdate();

The above one is used, when vue component is not refreshed correctly or Vue reactivity system does not work properly.

Note:

Calling forceUpdate will force the view to re-render.

The other ways to re-render the component are:
  • Re-loading the entire page
  • using V-if
  • Using Vue Built in forceUpdate method
  • The key changing on the component

Best way: Key changing technique on component

This is one of the easiest way to re-render the component.I think if you know dotnet,you probably know the app.config file, there you will find key value pairs. Suppose if you need to change any functionality on single page or entire application, then just you need to change key value in app.config.Thats it, will replace the whole application.The same concept is applied here also. Let us see the example, so that you can understand better,

                <template>
                    <component key="componentKeychange">
                <template>
                    export default {
                              data() {
                                return {
                                      componentKeychange: 0,
                                };
                              },
                              methods: {
                                forceRerender() {
                                  this.componentKeychange += 1;
                                }
                              }
                            }
                

Wheever forceRerender is called, our prop componentKeychange will change. When this happens, Vue will know that it has to destroy the component and create a new one.

Happy Vue Coding !!!