转换器(Converters)
优质
小牛编辑
134浏览
2023-12-01
如果您需要在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 。 管道符号| 用于应用转换器。 我们只使用dateFormat因为这是Aurelia注册DateFormatValueConverter 。
app.html
<template>
<require from = "./converters"></require>
<h3>${currentDate | dateFormat}</h3>
</template>
转换货币
这是货币格式的一个示例。 您会注意到该概念与上例中的概念相同。 首先,我们需要从command prompt安装numeral库。
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)');
}
}
视图模型只会生成一个随机数。 我们将此作为货币值使用并每秒更新一次。
app.js
export class App {
constructor() {
this.update();
setInterval(() => this.update(), 1000);
}
update() {
this.myCurrency = Math.random() * 1000;
}
}
我们的观点将显示随机生成的数字转换为货币。
app.html
<template>
<require from = "./converters"></require>
<h3>${myCurrency | currencyFormat}</h3>
</template>