Aurelia-converters
提供:Dev Guides
Aurelia-コンバーター
Aureliaアプリで一部の値を変換する必要がある場合は、手動で値を目的の形式に変換する代わりに converters を使用できます。
日付変換
デフォルトの日付値を特定の形式に変換する場合、 momentJS ライブラリを使用できます。 これは、日付を操作するために使用される小さなライブラリです。
C:\Users\username\Desktop\aureliaApp>jspm install moment
新しいファイル converters.js を作成しましょう。 このファイルを使用して、コンバーター固有のコードを追加します。 次のコマンドを使用するか、ファイルを手動で作成します。
C:\Users\username\Desktop\aureliaApp>touch converters.js
converter.js
このファイル内で、 moment ライブラリをインポートし、 DateFormatValueConverter を設定して、追加データなしで月、日、年の値のみを返します。 注意すべき重要なことは、Aureliaは ValueConverter で終わるすべてのクラスを認識できることです。 これが、クラス名が DateFormatValueConverter である理由です。 このクラスは dateFormat として登録され、後でビュー内で使用できます。
converters.js
import moment from 'moment';
export class DateFormatValueConverter {
toView(value) {
return moment(value).format('M/D/YYYY');
}
}
*app.js* では、現在の日付のみを使用します。 これがビューモデルになります。
app.js
export class App {
constructor() {
this.currentDate = new Date();
}
}
*custom-elements* の章で *require* について既に説明しました。 パイプ記号|コンバーターの適用に使用されます。 これは、Aureliaが *DateFormatValueConverter* を登録する方法であるため、 *dateFormat* のみを使用しています。
appl
<template>
<require from = "./converters"></require>
<h3>${currentDate | dateFormat}</h3>
</template>
通貨を変換する
これは通貨のフォーマットの例です。 概念は上記の例と同じであることに気付くでしょう。 まず、*コマンドプロンプト*から*数値*ライブラリをインストールする必要があります。
C:\Users\username\Desktop\aureliaApp>jspm install numeral
コンバーターは通貨形式を設定します。
converters.js
import numeral from 'numeral';
export class CurrencyFormatValueConverter {
toView(value) {
return numeral(value).format('($0,0.00)');
}
}
View-modelは、単に乱数を生成します。 これを通貨値として使用し、毎秒更新します。
app.js
export class App {
constructor() {
this.update();
setInterval(() => this.update(), 1000);
}
update() {
this.myCurrency = Math.random() * 1000;
}
}
ランダムに生成された数値が通貨として変換されたビューが表示されます。
appl
<template>
<require from = "./converters"></require>
<h3>${myCurrency | currencyFormat}</h3>
</template>