Ember传递查询参数失败,请求修正路由配置及跳转代码
解决Ember路由传递参数的问题
你现在的问题核心是对Ember路由参数的配置方式理解有误——路由的path属性里不能直接写?country=这种查询参数格式,得用Ember专门的参数配置逻辑来实现。下面分两种常见场景给出修正方案,你可以根据想要的URL形式选择:
方案一:使用查询参数(URL显示为 /purchase/purchaseEdit?country=SG)
这是你提到的"参数显示在URL查询串"的场景,步骤如下:
修正路由配置文件(route.js)
先把purchaseEdit的path改为正常路由路径,不需要在path里硬编码查询参数:this.route('purchase', { path: '/purchase' }, function () { this.route('purchaseDetails'); this.route('purchaseEdit'); // 默认path就是路由名,无需额外加?country= this.route('purchaseReview'); this.route('purchaseConfirmation'); });在PurchaseEdit路由类中配置查询参数
创建或修改app/routes/purchase/purchase-edit.js,添加查询参数的声明:import Route from '@ember/routing/route'; export default class PurchasePurchaseEditRoute extends Route { // 声明查询参数country queryParams = { country: { refreshModel: false, // 如果参数变化需要刷新模型,就设为true replace: false // 是否替换历史记录,按需设置 } }; // 可选:在路由中获取并传递参数给控制器 setupController(controller, model) { super.setupController(controller, model); controller.set('country', this.paramsFor(this.routeName).country); } }修正跳转代码
使用transitionTo时,通过queryParams对象传递参数:this.transitionTo('purchase.purchaseEdit', { queryParams: { country: "SG" } });
方案二:使用动态路由参数(URL显示为 /purchase/purchaseEdit/SG)
如果你更倾向于把参数作为URL的动态分段(而非查询串),可以这么改:
修正路由配置
在path中添加动态参数占位符:country:this.route('purchase', { path: '/purchase' }, function () { this.route('purchaseDetails'); this.route('purchaseEdit', { path: 'purchaseEdit/:country' }); // 动态参数占位符 this.route('purchaseReview'); this.route('purchaseConfirmation'); });修正跳转代码
直接把参数作为第二个参数传递给transitionTo:this.transitionTo('purchase.purchaseEdit', "SG");在路由中获取参数
可以在model钩子或setupController里拿到传递的参数:model(params) { // params.country就是你传递的"SG" console.log('当前国家参数:', params.country); // 这里可以根据参数请求对应数据 }
简单总结:你之前错误地把查询参数的写法放到了路由path里,这不符合Ember的路由规则,所以参数无法正常传递。按照上面的方案修改后,就能实现你想要的参数传递效果了。
内容的提问来源于stack exchange,提问作者user2024080
相关产品推荐
相关产品推荐

