首页 文章

使用VueJS加载动态组件和模板

提问于
浏览
6

我正在考虑将VueJS用于多页网站 . 在routing的官方示例中,它们表明您可以根据URL动态更改模板和组件,但它们仍然将所有HTML模板和JS组件放在一个文件中,这些文件一次性加载 .

我的网站将会非常庞大,我只想在需要时加载所有内容 . 所以我的问题是: How can I asynchronously load these HTML templates and JS components on demand when the URL is changed? 只显示如何修改上述路由示例以进行动态脚本加载会很有帮助 .

2 回答

  • 10

    更新:请参阅官方文档中的Async Components部分 .

  • 3

    硬编码,但工作 . 对于像我这样的初学者来说,Webpack解决方案太难了 .

    var router = new VueRouter({hashbang:false})
    var routerMap = {};
    
    router.beforeEach( function (transition) {
        var path = transition.to.path;
        if ((path != '/') && !(path in routerMap)) {
            _ajax('/reports/'+ path + '.html', function(res){//$.ajax replacement (async)
                routerMap[path] = {
                    component: {
                        template: res 
                    }
                }; 
                router.on(path, routerMap[path]);   //associate dynamically loaded component            
    
                transition.abort();     //abort current
                router.stop();                          
                router.start();         //restart router
                router.go(path);        //init new transition to the same path
            });//_ajax 
      } else 
            transition.next();          //default action for already loaded content
    });
    

相关问题