Detailed explanation of VueJs asynchronous dynamic loading block

  • 2021-08-03 08:39:55
  • OfStack

First, define the component as asynchronous loading


define(['jquery','vue'],function($,Vue){ 
  Vue.component('comp1',function(resolve){ 
    require(['component/comp1'],resolve); 
  }); 
  Vue.component('comp2',function(resolve){ 
    require(['component/comp2'],resolve); 
  }); 
  var b = new Vue({ 
    el:"#app", 
    data:{ 
      currentView:'comp1' 
    }, 
    methods:{ 
      toggleView:function(){ 
        console.log(this.currentView); 
        this.currentView = this.currentView=='comp1'?'comp2':'comp1'; 
      } 
    } 
  }); 
}) 

You can refer to the asynchronous components and dynamic components of vuejs for details. Then there is the code in html


<div id="app"> 
    <keep-alive><!--  Use keep-alive You can keep dynamically cut-out components in memory (just hidden and invisible), but when they come back, they will continue their previous state and data  --> 
    <component v-bind:is="currentView"></component> 
    </keep-alive> 
    <button type="button" v-on:click="toggleView"> Switch view</button> 
  </div> 

The advantage of this structure is that when the page is initialized and loaded, only the content related to the required component will be loaded, and the component that has not been switched to will not be loaded, which will speed up the page loading. At the same time, after each component is loaded once, switching out and cutting back will not repeat loading related content and rendering


Related articles: