gpt4 book ai didi

javascript - Ember.js 2、transitionTo 在一级路由中使用多个动态段

转载 作者:行者123 更新时间:2023-11-28 04:22:29 25 4
gpt4 key购买 nike

我使用的是 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 };
}

templates/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() 方法来解决这个问题。 这是正确的方法吗?

最佳答案

您不需要覆盖序列化 Hook ,默认情况下您将在路由模型 Hook 参数中获取动态段和queryParams。

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调用模型钩子(Hook),那么在参数中提供对象或模型总是提供所需的参数可以是字符串或数字。引用:https://guides.emberjs.com/v2.14.0/routing/defining-your-routes/#toc_dynamic-segments

关于javascript - Ember.js 2、transitionTo 在一级路由中使用多个动态段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45332459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com