Emberjs-route-url-rplc

提供:Dev Guides
移動先:案内検索

代わりにreplaceStateを使用したルーター更新URL

replaceStateトランジションを使用して、アイテムをブラウザーの履歴に追加しないようにすることができます。 これを指定するには、ルートで_queryParams_構成ハッシュを使用し、_replace_遷移をtrueに設定して_replaceState_遷移にオプトインします。

構文

Ember.Route.extend ({
   queryParams: {
      queryParameterName: {
         replace: true
      }
   }
});

以下の例は、replaceStateトランジションでURLを更新する方法を示しています。 新しいルートを作成し、_paramreplaceState_という名前を付け、_router.js_ファイルを開いてURLマッピングを定義します-

import Ember from 'ember';
//Access to Ember.js library as variable Ember
import config from './config/environment';
//It provides access to app's configuration data as variable config

//The const declares read only variable
const Router = Ember.Router.extend ({
   location: config.locationType,
   rootURL: config.rootURL
});

//Defines URL mappings that takes parameter as an object to create the routes
Router.map(function() {
   this.route('paramreplaceState');
});

//It specifies Router variable available to other parts of the app
export default Router;

次のコードで_app/templates/_の下に作成された_application.hbs_ファイルを開きます-

<h2>Update URL with replaceState</h2>
{{#link-to 'paramreplaceState'}}Click Here{{/link-to}}

上記のリンクをクリックすると、ページをクリックしてURLを変更するボタンが表示されます。 次のコードでparamreplaceState.hbsファイルを開きます-

//sending action to the addQuery  method
<button {{action 'change'}}>Replace State</button>
{{outlet}}

今ルートを入力するときにルーターによってレンダリングされるapp/controllers/の下に作成されたparamreplaceState.jsファイルを開きます-

import Ember from 'ember';
var words = "finddevguides";

export default Ember.Controller.extend ({
   queryParams: ['query'],
   actions: {
      change: function() {

        //assigning value of variable 'words' to the 'query' i.e. query parameter
         this.set('query', words);
      }
   }
});

次に、それぞれのコントローラーでRouteの_queryParams_構成を使用し、_app/routes/_の下に作成された_paramreplaceState.js_ファイルでreplace configプロパティをtrueに設定します。

import Ember from 'ember';

export default Ember.Route.extend ({
   queryParams: {
      query: {
        //assigning replace state as true
         replace: true
      }
   }
});

出力

エンバーサーバーを実行すると、次の出力が表示されます-

Ember.jsルーター更新URL replaceState

リンクをクリックすると、addQueryメソッドにアクションを送信するボタンが表示されます-

Ember.jsルーター更新URL replaceState

ボタンをクリックすると、「?」の右側にパラメータ値が表示されますURLで-

Ember.jsルーター更新URL replaceState