【问题标题】:Creating routes dynamically in Meteor在 Meteor 中动态创建路由
【发布时间】:2013-03-05 21:32:24
【问题描述】:

我正在使用meteor-router 包在我的应用程序中设置路线。但是,我需要能够“动态地”设置一些路线。这意味着我有一些“静态”路由和一些“动态”路由,它们会根据某些变量(特别是 URL 的一部分)而变化。
例如,如果用户访问 www.example.com/foo,我的路由应在所有 URL 前加上 foo,如果用户访问 www.example.com/bar,则所有路由都应以 bar 前缀。

伪代码:

Meteor.subscribe('bar', function(){
  var prefix = window.location.pathname.replace(/^\/([^\/]*).*$/, '$1');

  // "dynamic" routes, generated after 'subscribe' is ready
  Meteor.Router.add({
    prefix+'/': function() {
      // some code
      return 'mainTemplate';
    },
    prefix+'/welcome': 'welcome',
    prefix+'/foo': 'foo',
    prefix+'/bar': 'bar'
  });
)};

// "static" routes, independent of current URL
Meteor.Router.add({
  '/': 'home',
  '/admin': 'admin'
});

【问题讨论】:

    标签: routing meteor meteorite


    【解决方案1】:

    上面的设置应该可以工作,只需将每个路由更改为具有/ 前缀

    Routes = {}
    
    Routes['/' + prefix + '/welcome'] = function() { return 'welcome' };
    Routes['/' + prefix +' /foo'] = 'foo';
    ...
    
    Meteor.Router.add(Routes);
    

    【讨论】:

    • 这样不行。在您的示例中,如果我尝试直接在 Meteor.Router.add() 方法中连接,则会收到错误消息:SyntaxError: Unexpected token +。如果我尝试在Meteor.Router.add() 之前创建此变量并将该变量分配为某个 URL,则什么也不会发生...事实上,我关于“动态”设置路由的想法(在订阅准备好之后)可能不会像我想象的那样工作,但我仍然无法在我的两条路线中使用前缀工作。
    • 我已经更新了一点,它应该可以使用[] 方式来声明密钥
    • 是的,现在可以了...我在定义我的密钥时尝试使用[],但我尝试将它们放在Meteor.Router.add()...您的解决方案我想到了,但我没有'实际上没有尝试过 :) 非常感谢!
    猜你喜欢
    • 2017-07-26
    • 2020-07-17
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多