【问题标题】:Ember.js 2, transitionTo using multiple dynamic segments in first level routeEmber.js 2、transitionTo 在一级路由中使用多个动态段
【发布时间】:2018-01-02 02:25:49
【问题描述】:

我正在使用 Ember >= 2.13.x。

我需要在路由操作中使用transitionTo 才能进入另一条路由。

这里是演示 ember-twiddle:https://ember-twiddle.com/3cbb806f31f8d71a6c414452f4fc9ded

我有这种情况:

router.json

Router.map(function() {
  this.route('home', {path: '/'});
  this.route('categories', {path: 'categories'});
  this.route('category', {path: ':category_id'});
  this.route('posts', {path: 'posts'});
  this.route('post', {path: ':category_id/:post_id'}); //I have multiple synamic segments in here
});

routes/application.js

actions: {
    goToPost() {
        let post = this.store.findRecord('post', 1);
        this.transitionTo('post', post);
    }
}

routes/post.js

model(params) {
    return this.store.findRecord('post', params.id);
},

serialize(model) {
    console.log('model in serialize():', model);
    return { category_id: model.get('category.id'), post_id: model.id };
}

模板/application.hbs

<button type="button" {{action 'goToPost'}}>GoToPost with action (transitionTo)</button>

所以当我点击时,一切都按预期工作。

我在应用程序操作中获取模型,然后使用this.transitionTo('post', post);

在我的post 路由中,然后我有serialize(),我现在读到,它在存在动态段时用于 URL 组合。

我的问题:我的使用方法正确吗?

为什么我不能使用这样的东西:this.transitionTo('post', post.category.id, post.id); 并让model()post 路由中获取模型(从数据库或存储)?

我也尝试使用this.transitionTo('post', {category_id: post.category.id, post_id: post.id});,但显然post 路由model() 没有加载任何内容,因为它确实认为对象已经存在。

所以,我只能用serialize() 方法解决这个问题。 方法对吗?

【问题讨论】:

  • 你的类别路线有什么?
  • 重要吗?

标签: javascript ember.js ember-data transition ember-cli


【解决方案1】:

你不需要重写序列化钩子,默认情况下你会在路由模型钩子参数中获得动态段和查询参数。

model({post_id,category_id}) {
 return this.store.findRecord('post', post_id);
}

这里是twiddle

this.route('category', {path: 'category/:category_id'});
this.route('post', {path: 'post/:category_id/:post_id'});

我更喜欢添加相应的前缀,例如post,这样 URL 将变得容易区分。

如果你想让transitionTo调用模型钩子,那么在参数中提供对象或模型总是提供所需的参数,可以是字符串或数字。 参考:https://guides.emberjs.com/v2.14.0/routing/defining-your-routes/#toc_dynamic-segments

【讨论】:

  • 在你的游戏中你使用的是this.transitionTo('post', 1,2)。我改用this.transitionTo('post', post.get('category.id'), post.id)。我不知道为什么,但昨天在我的项目中它不起作用。非常感谢。
猜你喜欢
  • 2020-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多