如何在 ember 中显示 url 中的默认查询参数值?

How to show default query param value in url in ember?

如果查询参数值是默认值,

Ember 不会在 url 中显示查询参数。但我想展示一下。是否可以选择将此行为更改为显示而不是隐藏?

App.IndexController = Ember.ArrayController.extend({
  queryParams: ['type'],
  type: "horror"  // the default value, won't appear in URL or params
})

this guide section 中解释了默认值和序列化。不幸的是,它没有提供包含默认值的方法,我不确定是否有开箱即用的方法。

不过,有个小技巧。不要将默认值放在控制器中,而是使用 null 并在设置查询参数时在路由中设置默认值。这会让 Ember 认为它不是默认值,而从您的角度来看它是。

App.IndexRoute = Ember.Route.extend({
    resetController: function(controller) {
        controller.set('type', 'horror');
        return this._super.apply(this, arguments);
    }
});

App.IndexController = Ember.ArrayController.extend({
    queryParams: ['type'],
    type: null
});

我尝试将初始值设置为 null,但它并不总是有效:有时我的查询参数会出现在 URL 中,有时不会。如果查询参数不在 URL 中,我通过 window.history.replaceState() 操纵浏览器历史记录解决了这个问题。我将代码放在我的 setter 中 Ember.run.schedule('afterRender', this, function() {...}) 以便我的逻辑在 Ember 完成渲染后运行。

export default Ember.Controller.extend({
    setMyParam: function(newValue) {
        if (newValue !== null && typeof(newValue) !== 'undefined') {
            Ember.set(this, 'myParam', newValue);
            Ember.run.schedule('afterRender', this, function() {
                window.location.toString().match(/^(.+?)(\?.+)$/); //  = base URL,  = query params
                var queryParams = RegExp.;
                if (queryParams) {
                    if (queryParams.indexOf('myParam') === -1) {
                        console.log('No myParam in query parameters. Setting myParam=' + newValue);
                        window.history.replaceState({}, document.title, window.location.toString() + '&myParam=' + newValue);
                    }
                } else {
                    // No query parameters, so add it as the first query parameter
                    console.log('No query parameters, so adding myParam=' + newValue + ' as the first query parameter.');
                    window.history.replaceState({}, document.title, window.location.toString() + '?myParam=' + newValue);
                }
            });
         } else {
             console.log('setMyParam: newValue=' + newValue + ' is null or undefined. Not setting it!');
         }
    }
});