前言
在大型應(yīng)用中,我們可能需要將應(yīng)用拆分為多個小模塊,按需從服務(wù)器下載。為了進(jìn)一步簡化,Vue.js 允許將組件定義為一個工廠函數(shù),異步地解析組件的定義。Vue.js 只在組件需要渲染時觸發(fā)工廠函數(shù),并且把結(jié)果緩存起來,用于后面的再次渲染。
為什么需要異步組件,道理和webpack的按需加載是一樣的,如果一開始就加載所有的組件,那么是比較耗時的,所以我們可以將一些組件定義為異步組件,在需要使用的時候再進(jìn)行加載。
所以好處的話就顯而易見了 :
按需加載,可以節(jié)省首次加載的時間,提高速度,也算是一個性能優(yōu)化。 那么一個組件可能會被使用多次,按需加載的話也不會加載多次,第一次加載完成就會緩存下來,和webpack是一樣的,所以不用擔(dān)心最近讀Vue文檔的時候仔細(xì)看了一下異步組件部分,第一次看的時候一臉懵逼,看第二次還是有點(diǎn)迷茫,第三次就有點(diǎn)感覺了,第四次感覺有點(diǎn)明白了,遂記錄一下,下面是我寫的一個簡單Vue異步組件Demo。
實(shí)例代碼
index.html
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script> // 如果瀏覽器不支持Promise就加載promise-polyfill if ( typeof Promise === 'undefined' ) { var script = document.createElement( 'script' ); script.type = 'text/javascript'; script.src = 'https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.min.js'; document.head.appendChild( script ); } </script> <!-- 引入Vue --> <script src="https://cdn.jsdelivr.net/npm/vue"></script> </head> <body> <div id="app" style="font-size: 22px"> <!-- 異步組件async-comp --> <async-comp :list="['我是一個異步組件,','如果加載完成,','我就會在這里顯示']"></async-comp> </div> <!-- 引入main.js --> <script src="/main.js"></script> </body></html>異步組件Async-Comp.js,
注意,Async-Comp.js并沒有在index.html中引用,而是在下面的main.js中動態(tài)加載。
window.async_comp = { template: '/ <ol>/ <li v-for="item in list">{{ item }}</li>/ </ol>', props: { list: Array }};main.js
var vm = new Vue( { el: '#app', components: { /* 異步組件async-comp */ 'async-comp': function () { return { /** 要渲染的異步組件,必須是一個Promise對象 */ component: new Promise( function ( resolve, reject ) { var script = document.createElement( 'script' ); script.type = 'text/javascript'; script.src = '/Async-Comp.js'; document.head.appendChild( script ); script.onerror = function () { reject( 'load failed!' ); } script.onload = function () { if ( typeof async_comp !== 'undefined' ) resolve( async_comp ); else reject( 'load failed!' ) } } ), /* 加載過程中顯示的組件 */ loading: { template: '<p>loading...</p>' }, /* 出現(xiàn)錯誤時顯示的組件 */ error: { template: '/ <p style="color:red;">load failed!</p>/ ' }, /* loading組件的延遲時間 */ delay: 10, /* 最長等待時間,如果超過此時間,將顯示error組件。 */ timeout:3200 } } }} )
新聞熱點(diǎn)
疑難解答
圖片精選