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.

How to Create The VueJS Dropdown Component | Tutorial for Beginners

How to Create The VueJS Dropdown Component | Tutorial for Beginners

Learn how to make an easy VueJS Dropdown component that uses Vue Transitions to animate itself in. This component uses the very basic features of VueJS so it’s perfect for beginners.

Learn how to make an easy VueJS Dropdown component that uses Vue Transitions to animate itself in. This component uses the very basic features of VueJS so it’s perfect for beginners.

Source Code: https://github.com/TylerPottsDev/vue-dropdown

Vue.js components for reactive 3D rendering

Vue.js components for reactive 3D rendering

The vue-gl provides a set of components to render 3D graphics using three.js library.Vue.js components rendering 3D graphics reactively via three.js

Description:

The vue-gl provides a set of components to render 3D graphics using three.js library.Vue.js components rendering 3D graphics reactively via three.js

Install & Download:
# Yarn
$ yarn add vue-gl

# NPM
$ npm install vue-gl --save
Basic Usage:

Import the necessary libraries into the document.

<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/three"></script>
<script src="https://unpkg.com/vue-gl"></script>

Define objects.

<vgl-renderer id="vgl-canvas" style="width: 300px; height: 150px;">
    <vgl-scene>
        <vgl-sphere-geometry></vgl-sphere-geometry>
        <vgl-mesh-standard-material></vgl-mesh-standard-material>
        <vgl-mesh></vgl-mesh>
        <vgl-ambient-light></vgl-ambient-light>
        <vgl-directional-light></vgl-directional-light>
    </vgl-scene>
    <vgl-perspective-camera orbit-position="200 1 1"></vgl-perspective-camera>
</vgl-renderer>

Register components and start vue.

Object.keys(VueGL).forEach(name => {
  Vue.component(name, VueGL[name]);
});
new Vue({
  el: "#vgl-canvas"
});
Preview:

Download Details:

Author: vue-gl

Live Demo: https://vue-gl.github.io/vue-gl/

Download Link: https://github.com/vue-gl/vue-gl/archive/master.zip

Official Website: https://github.com/vue-gl/vue-gl

How to build a Reusable Vuejs modal component

How to build a Reusable Vuejs modal component

Modal is one of the essential components in the user interface. It’s good to display or receive a response from the user without moving to other pages. I’m going to build a Modal component and reusable in every page.

Modal is one of the essential components in the user interface. It’s good to display or receive a response from the user without moving to other pages. I’m going to build a Modal component and reusable in every page.

Timestamp
0:00 - Create HTML/CSS Modal Component
1:30 - Add conditional to Modal and control visibility (v-if and method)
4:58 - Create a custom component for Modal
8:22 - Pass data from parent to a child component by using props and slot
11:45 - Pass data from child to parent by using a custom event