What is a dynamic component?

Still give play to the language reading comprehension ability, dynamic component, should refer to is the dynamic change component, rather than fixed write dead, do not know my understanding accurate, let’s first look at the official explanation!

Declare a field with the

tag and predict that the field will be filled by a component using v-bind:is=’componentId’.

We are still the old rules, cui flower on the code!

    <div id="app">
        <button @click="onChangeComponentClick(1)">To ComponentA</button>
        <button @click="onChangeComponentClick(2)">To ComponentB</button>
        <button @click="onChangeComponentClick(3)">To ComponentC</button>
        <! -- declared area -->
        <component :is="componentId"></component>
    </div>
    
    <! -- Define component template content -->
    <template id="component-a">
      <div>component-a</div>
    </template>
    
    <template id="component-b">
      <div>component-b</div>
    </template>
    
    <template id="component-c">
      <div>component-c</div>
    </template>
    
    <script type="text/javascript">
      // Register component A/B/C
      var commponentA = {
        template: "#component-a"
      }
      
      var commponentB = {
        template: "#component-b"
      }
      
      var commponentC = {
        template: "#component-c"
      }
      
      var vm = new Vue({
        el: "#app".data:function(){
          return {
            componentId: commponentA
          }
        },
        
        methods: {// A click event passes in different values to determine which component the dynamic block is to mount
          onChangeComponentClick: function(type){
            switch (type) {
              case 1:
                this.componentId = commponentA;
              break;
              case 2:
                this.componentId = commponentB;
              break;
              case 3:
                this.componentId = commponentC;
              break; }}}});</script>
Copy the code

ComponentA (componentB (componentC) componentC (componentC (componentB) componentC (componentC) componentA (componentA) componentC (componentB) componentC (componentC) componentC (componentA) componentId (componentA)

When the code runs, the result is:

<div id="app">
    <div>component-a</div>
</div>
Copy the code

Replaces the area declared by

with componentA’s template. Then through the onChangeComponentClick method to change the componentId point, when the componentId point to change, the rendered content will also change.

Such a

to declare the area, through v-bind:is to bind the component (componentId), and then by changing the component (componentId) to change the presentation of the way can be called a dynamic component.

If you run the above code for yourself, you’ll notice that every time you switch component, something like this pops up in the browser console:

This means that every time we switch components, the template in the Component will be rerendered, and we know that DOM rendering is a performance consuming operation every time. The

tag tells Vue to cache the rendered component.

The code is as follows:

<keep-alive>
    <component :is="componentId"></component>
</keep-alive>
Copy the code

What is an asynchronous component?

Take a common phenomenon in life to see what asynchrony is: you boil water, wait for the water to boil, then go to brush your teeth, the water will boil a sound to tell you, and then you deal with the water after boiling things! After reading this to understand the official explanation is a bit of a light bulb!

In a large application, we might want to split the application into smaller code blocks and load a module from the server only when needed. To simplify, Vue allows you to define your component as a factory function that will parse your component definition asynchronously. Vue fires the factory function only when the component needs to be rendered, and caches the result for future rerendering.

Therefore, one of the most important features of asynchronous loading is that it can speed up page access. For example, we can make some non-first screen pages load asynchronously.

Defining asynchronous Components

Old custom cui hua, on the code:

  <div id="app">
    <async-example></async-example>
  </div>
  
  <template id="async-example">
    <div>I am an asynchronous component</div>
  </template>
   
  <script type="text/javascript">
    // Register the component
    var resCom = {
      template: "#async-example"
    }
    
    Vue.component('async-example'.function(resolve, reject){
      setTimeout(function(){
        // Pass the component definition to the resolve callback
        resolve(resCom);
      }, 1000);
    });
    
    var vm = new Vue({
      el: "#app"
    })
  </script>
    
Copy the code

In this code, we declare a variable resCom and give it a template pointing to async-Example, just as we do when we declare a local component.

We then create a factory function with Vue.component(‘async-example’, function (resolve, reject){}, which takes resolve and reject. These two arguments represent two callback methods. We can make the program load the defined resCom component asynchronously with resolve(resCom), or we can use resolve(‘ load the failed description ‘). To indicate a load failure. The setTimeout here is used only to simulate asynchronous operations. Of course, the above code can also be used as a partial component:

var vm = new Vue({
    el: '#app'.components: {
        'async-example': function (resolve, reject) {
            setTimeout(function () {
                resolve(resCom);
                // reject(' load failure description ');
            }, 1000); }}});Copy the code

Function (resolve, reject){reject… } looks like the definition of a Promise (click here to see the Promise details). In Vue, asynchronous components can also be defined as promises. This is the second way to define asynchronous components: Promise.

Here are some changes to the above code:

// Register the component
    var resCom = {
      template: "#async-example"
    };
    
    var promise = new Promise(function(resolve, reject){
      setTimeout(function(){
        resolve(resCom)
      }, 1000);
    });
    
    // Vue.component('async-example', function(resolve, reject){
    // setTimeout(function(){
    // // passes the component definition to the resolve callback
    // resolve(resCom);
    / /}, 1000);
    // });
    
    var vm = new Vue({
      el: "#app".components: {'async-example':function(){
          return promise
        }
      }
    })
Copy the code

In the code above we declare a Promise in the same way as the standard code, and then return the Promise when registering the asynchronous component.

We said earlier that Webpack + Vue-CLI is a Vue preferred build, and Webpack has direct built-in support for the Promise’s asynchronous component registry. When building a formal project with Webpack, we can also register an asynchronous component directly with import(‘./my-async-component’), and import(‘./my-async-component’) will return a Promise directly.

// Register globally
Vue.component(
  'async-webpack-example'.// The 'import' function returns a 'Promise' object.
  () = > import('./my-async-component'))// Local registration
new Vue({
  // ...
  components: {
    'my-component': () = > import('./my-async-component')}})Copy the code

The last type of asynchronous registration, which we call advanced asynchronous component registration, is a new type of asynchronous component registration in Vue2.3.0. Take a look at how high-level asynchronous components should be defined:

  <script type="text/javascript">
    // Register the component
    var resCom = {
      template: "#async-example"
    };
    
    var promise = new Promise(function(resolve, reject){
      setTimeout(function(){
        resolve(resCom)
      }, 2000);
    });
    
    var LoadingComponent = {
      template: '
       
Component displayed in load
'
}; var ErrorComponent = { template: '
Asynchronous component loading failed
'
}; // Vue.component('async-example', function(resolve, reject){ // setTimeout(function(){ // // passes the component definition to the resolve callback // resolve(resCom); / /}, 1000); // }); const AsyncComponent = function(){ return { // The component to be loaded (which should be a 'Promise' object) component: promise, // The component used when the asynchronous component is loaded loading: LoadingComponent, // The component used when the load fails error: ErrorComponent, // Display the delay time of the component when loading. The default is 200 milliseconds delay: 200.// If the timeout period is provided and the component loading has timed out, // Use the component used when the load failed. The default value is' Infinity ' // PS: ErrorComponent loading timeout. Timeout indicates that the loading failed. ErrorComponent is displayed. // For example, when we change the setTimeout in the Promise to 4000, we show the ErrorComponent timeout: 3000}}var vm = new Vue({ el: "#app".// Note that this is different from the previous method, because we are putting the method out to assign to the AsyncComponent variable components: {'async-example': AsyncComponent } })
</script> Copy the code

It can be seen that the configuration of high-level asynchronous components is more comprehensive and logically simpler than the configuration of the first two types of asynchronous components, so in the actual project use, we also prefer to use high-level asynchronous components to define asynchronous components.

Thank you for reading, if it helps you, welcome to the “CRMEB” nugget. Code cloud has our open source mall project, knowledge paid project, JAVA edition full open source mall system, learning and research welcome to use, old Iron easy point star bai, the boss reward five cents, cent you two cents, 😂😂 pay attention to keep in touch with us!