我已经成功地延迟加载组件,并且我已经成功地延迟加载模板,但我还没有成功地将这两者结合起来。
以下是我如何延迟加载组件:
// This is in my main.js
const router = new VueRouter({
routes: [
{ path: '/lazy', component: () => import('./lazy.js') }
]
})
// And this is in lazy.js
export default {
template: '<div>Lazy loaded component</div>'
}
这工作得很好,我可以看到直到我导航到 /lazy
后才下载 lazy.js
。
这里显示我延迟加载模板:
// All of this is in my main.js
const lazyTemplate = Vue.component('lazyComponent', function(resolve) {
fetch('./lazy.html')
.then(response => response.text())
.then(function(data) {
resolve({
template: data
});
});
});
const router = new VueRouter({
routes: [
{ path: '/lazy', component: lazyTemplate }
]
});
同样,这工作得很好,我可以看到直到我导航到 /lazy
后才下载 lazy.html
。
但我的主要问题是我不知道如何将这些组合到方法中。我如何“ native ”(没有即 webpack)延迟加载延迟加载模板的组件?
最佳答案
延迟加载模板和组件并异步加载,然后在解析 Promise 之前将它们添加在一起:
const lazyComponent = Vue.component('lazyComponent', function(resolve) {
Promise.all([
// fetch html template independently
fetch('./lazy.html').then(response => response.text()),
// fetch component js independently
import('./lazy.js')
]).then(([template, module] => {
// add template to component after both load
let component = module.default;
component.template = template;
// return component with template
resolve(component);
}));
});
const router = new VueRouter({
routes: [
{ path: '/lazy', component: lazyComponent }
]
});
关于javascript - 如何延迟加载组件和模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52682522/