javascript - 如何延迟加载组件和模板

标签 javascript vue.js lazy-loading vue-component vue-router

我已经成功地延迟加载组件,并且我已经成功地延迟加载模板,但我还没有成功地将这两者结合起来。

以下是我如何延迟加载组件:

// 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/

相关文章:

iphone - 动态 UITableViewCell 高度,延迟加载单元格中的图像

c# - DLL 延迟加载

javascript - 循环结束后重启 jQuery.each()

laravel - 在 vue 组件中使用 Laravel includes?

javascript - 如何使用多个选择器和事件更紧凑地编写此 jQuery 代码?

javascript - @单击复选框添加/删除数据

javascript - 使用 vue-router 的谷歌收件箱式导航

java - Hibernate 中的延迟加载

javascript - 包括 javascripts 不工作

javascript - .load() 函数不会加载 JavaScript