项目是用的vue-cli/webpack模板。
项目中有一个tab分页,其中每页内容和用户点击的栏目有关。
tab下显示内容区域,我写了一个组件:
<script>
export default {
props: ['content'],
render (h) {
let comp = require('../page/' + this.content + '.vue')
return h(comp, {})
}
}
</script>
这样可以使用,但这样最终会把所有的业务代码全部打包到app.js中,页面一加载所有的模块的都加载了。
我参考了下 vue-router 的懒加载,改成了 import
形式:
<script>
export default {
props: ['content'],
render (h) {
// let comp = require('../page/' + this.content + '.vue')
let comp = () => import('../page/' + this.content + '.vue')
return h(comp, {})
}
}
</script>
这样修改发现,comp返回的是 promise
,直接 render 就是死循环了。
查到 webpack.ensure
方法,改成如下方式:
<script>
export default {
props: ['content'],
render (h) {
require.ensure([], (require) => {
let comp = require('../page/' + this.content + '.vue')
return h(comp, {})
})
}
}
</script>
貌似 render 函数,不支持异步形式。
请问这个需要如何来处理?同时,是否需要额外配置 webpack呢?
To convert any .vue component from being a sync. to an async component the rule is as followed according to their API. (Not including SSR which as first answer says, is not possible until vue 2.4):
Anywhere in VueJS that accepts a
Component
(usually from acomponent
property) will also take a function that returns aPromise<Component>
This means if you have:
That it can also be async by changing it to:
The above example will only resolve the component async if it is scanned and resolved in the view template. So if you have that component wrapped in a
v-if
and the expression does not evaluate to true, then the component async code will never be fetched.The same applies to local component registration:
to be async you convert to: