【问题标题】:vuejs current timestamp movingvuejs当前时间戳移动
【发布时间】:2020-12-18 03:26:13
【问题描述】:

我有当前的时间戳函数,它返回日期和时间,但它不会移动(意思是:秒和分钟等只显示页面何时加载而不是实时)

我想要什么:我想要时间移动而不是静止的

代码

script

methods: {
  currentDateTime() {
      const current = new Date();
      const date =
        current.getFullYear() +
        "-" +
        (current.getMonth() + 1) +
        "-" +
        current.getDate();
      const time =
        current.getHours() +
        ":" +
        current.getMinutes() +
        ":" +
        current.getSeconds();
      const dateTime = date + " " + time;

      return dateTime;
    },
}

HTML

{{ currentDateTime() }}

screenshot

有什么想法吗?

【问题讨论】:

    标签: javascript typescript vue.js vuejs2


    【解决方案1】:

    currentDateTime() 只会执行一次。使用setInterval() 每1秒执行一次。

    data: {
        timestamp: ''
    },
    mounted: function () {
        setInterval(() => { this.currentDateTime() }, 1000)
      }
    }),
    methods: {
      currentDateTime() {
          const current = new Date();
          const date =
            current.getFullYear() +
            "-" +
            (current.getMonth() + 1) +
            "-" +
            current.getDate();
          const time =
            current.getHours() +
            ":" +
            current.getMinutes() +
            ":" +
            current.getSeconds();
          const dateTime = date + " " + time;
          this.timestamp = dateTime;
        },
    }
    

    HTML

    {{ timestamp }}
    

    【讨论】:

    • 别忘了clearInterval in beforeDestroy
    猜你喜欢
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 2011-12-26
    相关资源
    最近更新 更多