【问题标题】:ember replaceWith does not changes the urlember replaceWith 不会更改 url
【发布时间】:2019-10-09 13:27:14
【问题描述】:

如何对同一条路由执行一些replaceWith但参数不同?

路由声明为:

this.route('sampleRoute', { path: '/:param_name' });

这个 'sampleRoute' 路由重现了这个问题:在其中的replaceWith 之后,URL 没有改变。

let globalFlag = null;

export default Route.extend({
  afterModel() {

    console.log("welcome");

    if(globalFlag){
      console.log(this.router.location.getURL());
      console.log(this.paramsFor(this.routeName).param_name);
    } else {
      globalFlag = true;
      this.replaceWith(this.routeName, 'progValue');
    }
  }
});

尝试了 beforeModel、model、afterModel。如何在运行某些代码之前正确设置 URL?

http://localhost/sampleRoute/browserValue 测试这条路线会产生:

Expected output: 
    welcome
    welcome
    /sampleRoute/progValue
    progValue

Actual output:
    welcome
    welcome
    /sampleRoute/browserValue
    progValue

【问题讨论】:

  • AFAIK 路由器将停留在旧位置/URL,直到目标路由 afterModel 成功完成。所以你只是来早了。

标签: ember.js ember-router


【解决方案1】:

如果 /sampleRoute/ 之后的 URL 段不是动态的,我认为您正在寻找嵌套路由而不是查询参数。您的 router.js 文件将包含:

this.route('sampleRoute', function() {
  this.route('someNestedRoute');
});

或者如果段是动态的,那么你的 router.js 文件是:

this.route('sampleRoute');

重要的是,您不需要将参数指定为路由的 path 选项。

在您的模型中,replaceWith 为查询参数使用哈希:

import { set } from '@ember/object';

export default Route.extend({
  globalFlag: null,

  beforeModel(transition) {
    super.beforeModel(transition);

    if (this.globalFlag){
      console.log('flag set');
    } else {
      set(this, 'globalFlag', true);
      this.replaceWith(this.routeName, transition.to.queryParams);
    }
  }
});

但是我会质疑你在这里想要做什么。您应该能够让 ember 的路由和控制器为您管理查询参数,而根本不需要像这样 replaceWith。我会查看指南:https://guides.emberjs.com/release/routing/query-params/

【讨论】:

猜你喜欢
  • 2017-01-08
  • 2015-11-13
  • 2012-02-11
  • 1970-01-01
  • 2018-08-02
  • 2018-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多