今天就跟大家聊聊有关Vue中怎么实现一个异步组件,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
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" >
<!-- 异步组件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 >load failed!</p>\
'
},
/* loading组件的延迟时间 */
delay: 10,
/* 最长等待时间,如果超过此时间,将显示error组件。 */
timeout:3200
}
}
}
} )
看完上述内容,你们对Vue中怎么实现一个异步组件有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。