如何组合铁调子和力矩JS以显示HH:MM:SS格式的聚合物中



我正在尝试将我在计时器中使用的时间转换为HH:MM:SS格式使用Moment Js,但被卡住了。以下是我的代码。

<iron-timer id="timer" start-time="150" end-time="0" current-time="[[currentTime]]">
<moment-js date="[[_calculatedTime(currentTime)]]"></moment-js>
</iron-timer>

因此,当时间开始时,时间不会在格式化日期中更新。我该如何工作

这是我想到的,但是您的问题有些不完整,所以如果我走错的方式,请纠正我。

组件依赖性:聚合物2.5,铁接手2.1.2,Moment-JS 0.7.2

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Timer</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="import" href="../bower_components/polymer/polymer.html">
  <link rel="import" href="../bower_components/iron-timer/iron-timer.html">
  <link rel="import" href="../bower_components/moment-js/moment-js.html">
</head>
<body>
<dom-module id="moment-timer">
  <template>
    <iron-timer id="timer" start-time="150" end-time="0" current-time="{{currentTime}}"></iron-timer>
    <moment-js date="[[_toMilliSecs(currentTime)]]" format="HH:mm:ss" utc></moment-js>
  </template>
  <script>
    class MomentTimer extends Polymer.Element{
      static get is(){
        return 'moment-timer';
      }
      static get properties(){
        return {
          currentTime: Number
        }
      }
      _toMilliSecs(currentTime){
        return currentTime * 1000;
      }
      ready(){
        super.ready();
        this.$.timer.start();
      }
    }
    window.customElements.define(MomentTimer.is,MomentTimer);
  </script>
</dom-module>
<moment-timer></moment-timer>
</body>
</html>

有几件事要注意:

  1. 您必须在脚本中的某个地方启动计时器。我在Ready((回调中做到了这一点。确保首先致电super.ready()
  2. 您需要将currentTime属性作为毫秒传递到moment-js元素 - 我使用方法_toMilliSecs来做到这一点。
  3. 如Moment-JS中的一个演示示例中所示,您需要在moment-js元素上设置utc属性。这是为您的计数提供的开始参考所必需的。本质上,我们将其计算为从1970-01-01 00:00:00开始的时间,并将计时器相对于此设置。效果是相同的。

希望有帮助!

最新更新