【问题标题】:Filter Collections using iron-router使用 Iron-router 过滤集合
【发布时间】:2017-02-12 08:35:26
【问题描述】:

我有一个使用{{#each Collection}} 渲染我的收藏的模板,我正在使用 Iron-router 来路由这个模板,如下所示:

Router.route('/home', function () {
this.render('home');
this.layout('header');
});

如何使用“书籍”过滤器按钮,以便 Iron-router 将该过滤器应用于订阅,这样我只能看到我的收藏的过滤版本,如下所示:

Collection.find({category: "books"});

【问题讨论】:

    标签: meteor iron-router


    【解决方案1】:

    有很多方法可以解决这个问题,但一种简单的方法是定义一个以类别为参数的子路由:

    Router.route('/collections/:category',{
      name: 'collections',
      layoutTemplate: 'header',
      data(){
        return Collections.find({category: this.params.category});
      }
    });
    

    然后你的按钮代码可以只做Router.go('/collections/books'),但你现在可以有多个按钮,每个按钮都绑定到不同的类别。

    【讨论】:

    • 您的回答似乎很有希望,但它对我不起作用。可能是因为对“收藏”模板有误解,所以我把名字改成了“家”。
    • name 应该是您要在路线上加载的模板的名称。如果您有 layoutTemplate,则该模板必须包含 {{> yield}} 才能插入路由模板。
    【解决方案2】:

    正如这里https://guide.meteor.com/data-loading.html#organizing-subscriptions 建议的那样,您可以在模板中而不是在路由中管理您的订阅。所以你可以这样做:

    import {ReactiveDict} from 'meteor/reactive-dict';
    import {Template} from 'meteor/templating';
    
    Template.home.onCreated(function(){
      var that = this;
      that.state = new ReactiveDict();
      //that.state.set('selected-category',YOUR_DEFAULT_CATEGORY);
      that.autorun(function(){
        that.subscribe('subscription-name',that.state.get('selected-category'));
      });
    });
    
    Template.home.events({
      'click .js-category':function(e,tpl){
        let category = tpl.$(e.currentTarget).data('category');
        tpl.state.set('selected-category',category); 
      }
    }); 
    

    在你的模板中:

    <button type="button" data-category="books" class="js-category">Books</button>
    

    希望这将帮助您找到适合您的解决方案

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-17
      • 2017-06-17
      • 1970-01-01
      • 2016-10-31
      • 1970-01-01
      • 2016-02-27
      • 1970-01-01
      相关资源
      最近更新 更多