Vue异步组件Demo
生活随笔
收集整理的這篇文章主要介紹了
Vue异步组件Demo
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Vue異步組件Demo
在大型應用中,我們可能需要將應用拆分為多個小模塊,按需從服務器下載。為了進一步簡化,Vue.js 允許將組件定義為一個工廠函數,異步地解析組件的定義。Vue.js 只在組件需要渲染時觸發工廠函數,并且把結果緩存起來,用于后面的再次渲染。
下面是我寫的一個簡單Vue異步組件Demo。
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-polyfillif ( 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中動態加載。
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>'},/* 出現錯誤時顯示的組件 */error: {template: '\<p style="color:red;">load failed!</p>\'},/* loading組件的延遲時間 */delay: 10,/* 最長等待時間,如果超過此時間,將顯示error組件。 */timeout:3200}}}
} ) see github
原文地址:https://segmentfault.com/a/1190000012561857
轉載于:https://www.cnblogs.com/lalalagq/p/9960394.html
總結
以上是生活随笔為你收集整理的Vue异步组件Demo的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 看朋友圈和空间的时候,偶尔会感到身边朋友
- 下一篇: 好听的金毛狗狗名字公