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.
Update: 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] = {
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With