在大型应用中,咱们可能须要将应用拆分为多个小模块,按需从服务器下载。为了进一步简化,Vue.js 容许将组件定义为一个工厂函数,异步地解析组件的定义。Vue.js 只在组件须要渲染时触发工厂函数,而且把结果缓存起来,用于后面的再次渲染。
下面是我写的一个简单Vue异步组件Demo。javascript
<!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>
window.async_comp = { template: '\ <ol>\ <li v-for="item in list">{{ item }}</li>\ </ol>', props: { list: Array } };
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 } } } } )