异步组件
- 异步组件也是一个函数, 只不过这个函数使用Promise,函数有一个返回值
<body>
<div id="app">
<async-com></async-com>
</div>
</body>
<script>
var result = new Promise(function( resolve, reject ){
resolve({
template: '<div> 异步组件 </div>'
})
})
Vue.component('AsyncCom',async () => {
const tpl = await result.then( res => res)
return tpl
})
// Vue.component('async-com', function (resolve, reject) {
// setTimeout(function () {
// // 向 `resolve` 回调传递组件定义
// resolve({
// template: '<div>I am async!</div>'
// })
// }, 1000)
// })
new Vue({
el: '#app'
})
</script>
异步组件的封装
const asyncCom = {
createAsyncCom({
selector,
asyncComName,
methods,
data,
watch,
computed,
filters,
directives,
components,
delay}){
var result = new Promise(function( resolve, reject ){
resolve({
template: selector,
methods,
data,
watch,
computed,
filters,
directives,
components
})
})
setTimeout(()=>{
Vue.component(asyncComName,async () => {
const tpl = await result.then( res => res)
return tpl
})
},delay)
}
}
export default {
createAsyncCom: asyncCom.createAsyncCom
}