Loading a dynamic component and template using VueJS

I am considering using VueJS for a multi-page website. In the official routing example, 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 a single file that loads immediately.

My site will be quite large, and I want to download everything only as needed. So my question is: How can I asynchronously load these HTML templates and JS components on demand when changing the URL? It would be useful to simply show how the above routing example can be modified for dynamic script loading.

+5
source share
2 answers

Update: See Async Components in white papers.

+10
source

Hard coded, but work. Webpack's solution is too complicated 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 }); 
+3
source

Source: https://habr.com/ru/post/1203588/


All Articles