本步骤提供了一个带有模板的示例元素。现在试着导入你的指令,然后在模板中使用它。

import {timeAgo} from './time-ago.js';

接下来,在 TimeAgoExample 类定义上方的模块级别创建一个 Date 对象,用于传递给指令,先看看它是否能正常工作:

const timeCreated = new Date();

@customElement('time-ago-example')
export class TimeAgoExample extends LitElement {
...
const timeCreated = new Date();

export class TimeAgoExample extends LitElement {
...

然后在模板中调用该指令:

return html`
<p>This page was rendered ${timeAgo(timeCreated)}.</p>
`;

你应该能看到指令将 Date 输出为字符串。下一步将把它格式化为已过去的时间。