7

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.

2 Answers 2

9

Update: see Async Components section in the official docs.

Sign up to request clarification or add additional context in comments.

2 Comments

Hello, Evan. Does vue.js get something like templateUrl now? I can only find things like using with webpack. This will restrict by deploy environment. eg. I have a site built with Angular on GitHub pages without pre-building, everything would be newest as I push the source code to GitHub. This is a typical sense that I cannot use webpack.
Because links (like this one) break it's useful to add the actual code in the answer where we know it will last.
3

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
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.