javascript 使用 VueJS 动态加载组件和模板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26093526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamic component and template loading with VueJS
提问by Migwell
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.
我正在考虑将 VueJS 用于多页网站。在路由的官方示例中,它们表明您可以根据 URL 动态更改模板和组件,但它们仍然将所有 HTML 模板和 JS 组件放在一个文件中,并且一次加载。
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 demandwhen the URL is changed?It would be helpful to just show how the above routing example could be modified for dynamic script loading.
我的网站将非常大,我只想在需要时加载所有内容。所以我的问题是:当 URL 更改时,如何按需异步加载这些 HTML 模板和 JS 组件?仅展示如何修改上述路由示例以进行动态脚本加载会很有帮助。
回答by Evan You
Update: see Async Componentssection in the official docs.
更新:请参阅官方文档中的异步组件部分。
回答by Denis Bogachev
Hardcoded, but work. Webpack solution is too hard for beginners, like me.
硬编码,但工作。Webpack 解决方案对于像我这样的初学者来说太难了。
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
});