Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic component and template loading with VueJS

I'm considering using VueJS for a multi page website. In the official example of routing, they show that you can dynamically change the template and component based on the URL, but they still have all the HTML templates and JS components in one file that's loaded all at once.

My website is going to be quite large, and I want to load everything only when required. So my question is: How can I asynchronously load these HTML templates and JS components on demand when the URL is changed? It would be helpful to just show how the above routing example could be modified for dynamic script loading.

like image 975
Migwell Avatar asked Sep 29 '14 06:09

Migwell


2 Answers

Update: see Async Components section in the official docs.

like image 76
Evan You Avatar answered Oct 20 '22 00:10

Evan You


Hardcoded, but work. Webpack solution is too hard for beginners, like me.

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
});
like image 42
Denis Bogachev Avatar answered Oct 20 '22 01:10

Denis Bogachev