Aurelia - 转换器

如果您需要在Aurelia应用中转换某些值,则可以使用转换器,而不是手动将值转换为所需格式.

转换日期

当我们想要将默认日期值转换为某种特定格式时,我们可以使用 momentJS 库.这是一个用于操作日期的小型库.

C:\Users\username\Desktop\aureliaApp>jspm install moment

让我们创建一个新文件 converters.js .我们将使用此文件添加转换器特定代码.使用以下命令或手动创建文件.

C:\Users\username\Desktop\aureliaApp>touch converters.js

converter.js

在此文件中,我们将导入时刻库并设置 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>

Aurelia Converters Date

转换货币

这是货币格式的示例.您会注意到该概念与上例中的概念相同.首先,我们需要从命令提示符安装数字库.

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>

Aurelia Converters Currency