Vue-router: 怎样按需加载相关的模块?

Created on 13 Jan 2016  ·  11Comments  ·  Source: vuejs/vue-router

router.map({
    '/page1':{
      component: require('./p1'),
    },
    '/page2':{
      component: require('./p2'),
    },
    '/page3':{
      component: require('./p3'),
    }
  });

p1,p2,p3的内容为AMD模块:
define(function(require, exports, module){
require('jquery');
 var Vue = require('vue');
    var p1 = Vue.extend({
          template:'<h2>p1 Loaded!</h2>'
        });
    return p1;
});

我的意思是 怎么只在路由匹配到相关的模块时再去加载相应的模块,而不是路由初始化时就加载所有模块的资源,因为p1,p2,p3....可能还会引用很多的资源,怎么样做到按需加载呢,求解!

Most helpful comment

All 11 comments

@yyx990803 谢谢小尤,中文文档请同步更新哦

@yyx990803 也是动态组件的问题

背景
业务模块比较多,一个个配置路由比较繁琐;
而且我想在开发的时候更多关注业务本身,所以尽量简化配置;
我想只对特殊的路由手动配置,大部分业务模块的路由由目录路径决定。

http://vuejs.github.io/vue-router/en/lazy.html 这里提到的动态组件载入,针对很多的模块需要动态载入的时候也不是一个很好的办法。即使用 webpack,也还是要很多的配置。

于是,我做了如下事情:
1、做了个模块加载器插件,实现直接 require("path/to/someComponent.vue") 就得到 Component;
2、我在 router.beforeEach 钩子中根据 transition.to.path 来找到业务模块路径,然后用模块加载器加载该模块;

如下代码,我用了 router.on 来绑定路由:

router.beforeEach(function (transition) {
    if (!transition.to.matched) {
        var path = transition.to.path;
        require.async('./view/' + path + '.vue', function(Component){
            if (Component) {
                router.on(path, {component: Component});
                //transition.redirect(path);
                transition.next();
            }
            else {
                transition.abort();
            }
        });
    } else {
        transition.next();
    }
    window.scrollTo(0, 0);
});

问题:在 beforeEach 钩子中,我找不到方法来动态设置模块。router.on 看起来对本次路由匹配不生效,得等到下次。
我甚至尝试了 transition.redirect(path) ,但是会产生意外的重定向。

有木有更好的办法呢?期待您的解答。谢谢 :)

路由配置如果能像 director 那样支持正则就更好了

router.on("([\w-]+)", function(resolve) {
    var path = ?
    require.async(path, resolve);
})

还是有问题,子路由中使用出错。
https://github.com/vuejs/vue-router/issues/366
应该是路径问题,因为浏览器默认去找这个文件:
http://localhost:8080/inbox/message/8.example.build.js

但webpack打包的路径是:
http://localhost:8080/8.example.build.js

因此加载出错。

@niceue 找到办法了咩?

要怎么解决模块中引用的其它组件分开打包?
A.vue里引用了xx.vue,B.vue里也引用了xx.vue,结果会分别打包到各自己JS中去!

@yyx990803 your page is 404 file not found

@transtone 我也遇到了这个问题,请问你怎么解决的

vue如何异步加载js

Was this page helpful?
0 / 5 - 0 ratings