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-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中动态加载。

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

最新文章

  1. 使用 Arduino 和 LM35 温度传感器监测温度
  2. php递归获取顶级父类id
  3. Ubuntu 修改hosts
  4. spring mvc(2):请求地址映射(@RequestMapping)
  5. 第二章:Posix IPC
  6. Java中Atomic包的实现原理及应用
  7. editplus快捷键大全
  8. Redis源码研究--跳表
  9. 四、IP地址转换
  10. yii2源码学习笔记(十八)
  11. SQL Server 中同时操作的例子:
  12. R语言学习之主成分分析法的R实践
  13. JQuery和JS操作LocalStorage/SessionStorage的方法
  14. 漫谈程序员(十)大白菜装机版安装win7系统使用教程
  15. C++ 类模板基础知识
  16. java 连接sqlserver数据库
  17. AngularJS controller as vm方式
  18. Apache Ignite 学习笔记(二): Ignite Java Thin Client
  19. Python WSGI开发随笔
  20. apt错误

热门文章

  1. set 集合————两个数组的交集
  2. 10、Latent Relational Metric Learning via Memory-based Attention for Collaborative Ranking-----基于记忆注意的潜在关系度量协同排序
  3. cron 和anacron 、日志转储的周期任务
  4. STM32 抢占优先级和响应优先级
  5. 【Codeforces Round #476 (Div. 2) [Thanks, Telegram!] D】Single-use Stones
  6. WCF与WEB API区别
  7. Android自己定义百度地图缩放图标
  8. JAVA学习之 异常处理机制
  9. Javaee 应用分层架构
  10. 认识一下Kotlin语言,Android平台的Swift