How do I Force a Vue Component to Re-render? (Method introduction)

How do I Force a Vue Component to Re-render? (Method introduction)

Sometimes it's not enough to rely on Vue's response to update the data. Instead, we need to manually re-render the component to update the data.

Sometimes it's not enough to rely on Vue's response to update the data. Instead, we need to manually re-render the component to update the data. Or we might just want to leave the current DOM and start over. So how do you get Vue to re-render the components in the right way?

The best way to force Vue to re-render a component is to set a **`:key` **on the component. When you need the component to be re-rendered, you just change the value of the key and Vue will re-render the component.

This is a very simple solution.

Of course, you might be more interested in other ways:

  • Simple and crude way: reload the entire page
  • Improper way: use v-if
  • Better way: use Vue's built-in forceUpdate methods
  • The best way: be on the component key change

Simple and crude way: reload the entire page


This is equivalent to restarting your computer every time you want to close the application.

This approach may be useful, but it is a very bad solution. Don't do it , let's take a look at a better way.

Improper way: use v-if

v-if Instruction, which is true only rendered when the component is active. If so false , the component does not exist in the DOM .

Let's see v-if how it works. In template it, add `v-if instructions:

<template>
  <my-component v-if = "renderComponent" />
</ template>

In script using nextTick the method of

<script>
  export default {
    data () {
      return {
        renderComponent: true,
      };
    },
    methods: {
      forceRerender () {
        // remove the my-component component from the DOM
        this.renderComponent = false;

        this. $ nextTick (() => {
          // add my-component component in DOM
          this.renderComponent = true;
        });
      }
    }
  };
</ script>

The above process is roughly as follows:

  • At first renderComponent set true, thus rendering my-component components
  • When we call forceRerender, we immediately renderComponent set to false
  • We stop rendering my-component because the v-if instruction now calculates as false
  • Set it back in the nextTick method renderComponent true
  • When the v-if calculation result for the instruction true, the rendering again my-component

In this process, two parts are more important

First we have to wait until nextTick otherwise we will not see any changes.

In Vue , a tick is a DOM update cycle. Vue will collect all updates made in the same tick, and at the end of the tick, it will render the content in the DOM based on those updates. If we don't wait until the next tick, our renderComponent update will be cancelled automatically and nothing will change.

Secondly, when we render for the second time, Vue will create a completely new component. Vue will destroy the first one and create a new one, which means our new one my-component will go through all its lifecycles as normal- created and so mounted on.

Alternatively, it nextTick can be used with promises:

forceRerender () {
  // remove the my-component component from the DOM
  this.renderComponent = false;

  this. $ nextTick (). then (() => {
    this.renderComponent = true;
  });
}

However, this is not a good solution, so let's do what Vue wants us to do

Better method: forceUpdate method


This is one of the two best ways to solve this problem, both of which are officially supported by Vue.

Normally, Vue responds to changes in dependencies by updating the view. However, when we call forceUpdate, it is also possible to force an update, even if all dependencies have not actually changed.

Here are the biggest mistakes most people make when using this method.

If Vue updates automatically when things change, why do we need to force an update?

The reason is that sometimes Vue's response system can be confusing. We think Vue will respond to changes in a property or variable, but this is not the case. In some cases, Vue's response system did not detect any changes at all.

So just like the previous method, if you need this to re-render your component, there may be a better way.

There are two different methods that can be called on the component instance itself and globally forceUpdate:

// global
import Vue from 'vue';
Vue.forceUpdate ();

// use component instance
export default {
  methods: {
    methodThatForcesUpdate () {
      // ...
      this. $ forceUpdate ();
      // ...
    }
  }
}

Important: This does not update any computed properties, the call forceUpdatesimply forces the view to be re-rendered.

The best way: be on the component key change


In many cases, we need to re-render the component.

To do this correctly, we will provide a key property so that Vue knows that a particular component is associated with a particular piece of data. If it key stays the same, it won't change the component, but if key it changes, Vue knows that it should delete the old component and create a new one.

Just what we need!

But first, we need to take a short walk to understand why it is used in Vue key.

Why do we need to use keys in Vue


Once you understand this, then this is a small step to understand how to force a re-render in the right way.

Suppose we want to render a list of components with one or more of the following:

  • Have local status
  • Some kind of initialization process, usually in created or mounted hook
  • Unresponsive DOM operations via jQuery or normal api If you sort the list or update it in any other way, you need to re-render some parts of the list. However, you don't want to re-render everything in the list, but just re-render the changed content.

To help Vue keep track of what has changed and has not changed, we provide a key property. The index of the array is used here because the index is not bound to a specific object in the list.

const people = [
  {name: 'Evan', age: 34},
  {name: 'Sarah', age: 98},
  {name: 'James', age: 45},
];

If we render it using the index, we get the following result:

<ul>
  <li v-for = "(person, index) in people": key = "index">
    {{person.name}}-{{index}}
  </ li>
</ ul>

// Outputs
Evan-0
Sarah-1
James-2

If you delete it Sarah, you get:

Evan-0
James-1

The James associated index is changed, even if James it is still James. James Will be re-rendered, which is not what we want.

So here, we can use only id as key

const people = [
  {id: 'this-is-an-id', name: 'Evan', age: 34},
  {id: 'unique-id', name: 'Sarah', age: 98},
  {id: 'another-unique-id', name: 'James', age: 45},
];

<ul>
  <li v-for = "person in people": key = "person.id">
    {{person.name}}-{{person.id}}
  </ li>
</ ul>

We removed from the list Sarah before, Vue deleted Sarah and James components, and then to James create a new component. Now Vue knows that it can keep Evan and James keep these two components, all it has to do is remove Sarah.

If we add one to the list person, Vue also knows that all existing components can be kept, and only a new component needs to be created and inserted in the right place. This is very useful, when we have more complex components, they have their own state, have initialization logic, or do any type of DOM operation, it is very helpful for us.

So let's see if we can use the best method to re-render the component.

Change the key to force the component to re-render


Finally, this is the best way to force Vue to re-render the component (I think).

We can adopt this key strategy of assigning to child components, but every time we want to re-render the component, we just need to update it key.

This is a very basic method

<template>
  <component-to-re-render: key = "componentKey" />
</ template>


export default {
  data () {
    return {
      componentKey: 0,
    };
  },
  methods: {
    forceRerender () {
      this.componentKey + = 1;  
    }
  }
}

Each time it orceRerender is called, ours componentKey change. When this happens, Vue will know that it must destroy the component and create a new component. What we get is a child component that will reinitialize itself and "reset" its state.

If you do need to re-render something, choose a key change method over another.

vuejs re-render-component

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Hire Dedicated VueJS Developers

Want to Hire VueJS Developer to develop an amazing app? **[Hire Dedicated VueJS Developers](https://hourlydeveloper.io/hire-dedicated-vue-js-developer/ "Hire Dedicated VueJS Developers")** on the contract (time/project) basis providing regular...

How to Publish a Vuejs Component on NPM

I will explain you now how to publish your own VueJs component on npm with a minify and ES5 build.

Exploring React Renders: Different ways a component gets re-rendered.

We would be looking at different scenarios/cases on how React components render and re-renders. This is not to be an introductory post so, some prior knowledge of React would be a prerequisite.

Server side rendering Styled-Components with NextJS

Server side rendering Styled-Components with NextJS - I switched to styled-components for most of my projects nearly a year now but never used it with Next.js until recently. This might be a bit late to the party but I feel it’s definitely worth sharing the neat trick of ServerStyleSheets...

Webcam component for VueJs

vue-web-cam .Webcam component for VueJs. See this for browser compatibility.