首先定義組件為異步加載
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'; } } }); })
具體可以參考vuejs的異步組件和動(dòng)態(tài)組件。然后是html里面的代碼
<div id="app"> <keep-alive><!-- 使用keep-alive可以讓動(dòng)態(tài)被切出去的組件繼續(xù)保存在內(nèi)存中(只是隱藏看不到),卻回來之后會(huì)繼續(xù)之前的狀態(tài)和數(shù)據(jù) --> <component v-bind:is="currentView"></component> </keep-alive> <button type="button" v-on:click="toggleView">切換view</button> </div>
這種結(jié)構(gòu)的好處是,頁面初始化加載的時(shí)候只會(huì)加載需要的那個(gè)組件相關(guān)的內(nèi)容,沒切換到的那個(gè)組件不加載,使頁面加載的速度加快。同時(shí),每個(gè)組件加載過一次之后切換出再切回來不會(huì)重復(fù)加載相關(guān)內(nèi)容和重復(fù)執(zhí)行渲染
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
網(wǎng)友關(guān)注