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 ponent based on the URL, but they still have all the HTML templates and JS ponents 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 ponents 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.
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 ponent based on the URL, but they still have all the HTML templates and JS ponents 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 ponents 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.
Share Improve this question asked Sep 29, 2014 at 6:12 MigwellMigwell 20.1k24 gold badges104 silver badges180 bronze badges2 Answers
Reset to default 9Update: see Async Components section in the official docs.
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] = {
ponent: {
template: res
}
};
router.on(path, routerMap[path]); //associate dynamically loaded ponent
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
});