【问题标题】:EmberJS: Retransition to current route and reset dynamic segmentEmberJS:重新过渡到当前路线并重置动态段
【发布时间】:2018-02-08 06:22:19
【问题描述】:

我有一些路线定义如下:

Router.map(function() {
      this.route('foo', function() {
         this.route('bar');
         this.route('bar', {path: 'bar/:fooid'});
      });
      // ...
});

/foo/bar/:fooid 中的动态段是可以根据某些规则进行验证的 id。为了简化示例,我们假设 :fooid 必须正好包含 3 位数字。

如果像 /foo/bar/1234567 一样传递了无效值,我想将 url 重置为 foo/bar/

简化的 foo.bar 路由:

export default Ember.Route.extend({

  model (params) {
     // If fooid is invalid, set model.fooid.isValid to false
  },

  afterModel (model, transition) {
     // If fooid is invalid...
     this.transitionTo('/foo/bar/');
  }

});

验证过程本身有效,但我无法摆脱 url 中错误的 :fooid 参数!

如果我转换到不同的路线,它工作正常。

Ember 版本是 2.14

【问题讨论】:

    标签: ember.js


    【解决方案1】:

    我认为您需要使用默认的索引路由,它将为每条路由提供。

    this.route('foo', function() {
        this.route('bar', function () {        
            this.route('child', { path: ":fooid" });
        });
    });
    

    这里是网址/foo/bar

    route- app/routes/foo/bar/index.js  
    controller - app/controllers/foo/bar/index.js  
    template - app/templates/foo/bar/child.hbs 
    

    对于 URL /foo/bar/123

    route- app/routes/foo/bar/child.js  
    controller - app/controllers/foo/bar/child.js  
    template - app/templates/foo/bar/index.hbs
    

    如果你有上述结构,那么你可以从foo.bar.child 过渡到foo.bar.index 路由。

    app/routes/foo/bar/child.js 的模型钩子中你可以说this.transitionTo('foo.bar.index')。它会带你到那条路线。

    注意:
    1.如果您定义了动态段,那么您需要提供有效值。否则 ember 将不允许进入路由。当您直接从 URL 尝试时,我不是如何为您制定 foo/bar/
    2.最好使用transitionTo方法的路由名称而不是直接URL。 2. 可以试试http://alexspeller.com/ember-diagonal/route/post 更好的理解ember路由模型


    beforeModel钩子中,你可以检查传入的参数fooid,如果它的状态错误,那么你可以使用默认值transitionTo

    beforeModel(transition){
     // you can transition.params[transition.targetName].fooid to get the value.
     //then try transitionTo the same route with default value
     this.transitionTo('foo.bar',defaultValue)
    }
    

    【讨论】:

    • transition.abort() 然后transition.retry() 可能会清除 queryParams 。对此有一个未解决的问题。你甚至可以试试那个。
    • 非常感谢!你知道我可以使用哪个默认值吗? {fooid: null} 将 url 更改为 /foo/bar/null/{}{fooid: ''} 将导致错误:You must provide param fooid to generate.。如果我手动浏览到 /foo/bar/ 一切正常。我怎样才能使用transitionTo 做到这一点?
    • 抱歉给您带来了困惑..我说的是 queryParam,但您使用的是动态段。默认值的东西只适用于查询参数。
    • 再次感谢,这是我正在寻找的输入。
    猜你喜欢
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-15
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 2012-10-18
    相关资源
    最近更新 更多