Aurelia 转换器
如果您需要在 Aurelia 应用程序中转换某些值,您可以使用
转换器 而不是手动将值转换为所需的格式。
转换日期
当我们想要将默认日期值转换为某种特定格式时,我们可以使用
momentJS 库。这是一个用于操作日期的小型库。
C:\Users\username\Desktop\aureliaApp>jspm install moment
让我们创建一个新文件
converters.js。我们将使用此文件添加转换器特定代码。使用以下命令或手动创建文件。
C:\Users\username\Desktop\aureliaApp>touch converters.js
转换器.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>
转换货币
这是货币格式的示例。您会注意到该概念与上述示例中的概念相同。首先,我们需要从
命令提示符安装
数字库。
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;
}
}
我们的视图将显示随机生成的数字转换为货币。
app.html
<template>
<require from = "./converters"></require>
<h3>${myCurrency | currencyFormat}</h3>
</template>
