如何在不刷新页面的情况下在 vue.js 中更新当前时间戳?

Nan*_*van 2 javascript vue.js vue-component vuejs2

在我的 vue 应用程序中,我使用一种方法来获取当前时间戳,我正在获取当前时间和日期,但只有在刷新页面后才会更新,我希望它在不刷新页面的情况下动态更新。

我想我需要包括像 set interval 不知道如何实现的东西

<html>
   <head>
      <title>VueJs Introduction</title>
      <script type = "text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js">
      </script>
   </head>
   <body>
      <div id = "intro" style = "text-align:center;">
         <h1>{{ timestamp }}</h1>
      </div>
      <script type = "text/javascript">
         var vue_det = new Vue({
            el: '#intro',
            data: {
               timestamp: ''
            },
            created() {
                this.getNow();
            },
            methods: {
                getNow: function() {
                    const today = new Date();
                    const date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
                    const time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
                    const dateTime = date +' '+ time;
                    this.timestamp = dateTime;
                }
            }
         });
      </script>
   </body>
</html>
Run Code Online (Sandbox Code Playgroud)

Bou*_*him 5

在创建的钩子中添加 1 秒的范围时间,例如:

setInterval(() => {
  this.getNow();
}, 1000)
Run Code Online (Sandbox Code Playgroud)

完整示例

setInterval(() => {
  this.getNow();
}, 1000)
Run Code Online (Sandbox Code Playgroud)
var vue_det = new Vue({
  el: '#intro',
  data: {
    timestamp: ''
  },
  created() {
    setInterval(() => {
      this.getNow();
    }, 1000)
  },
  methods: {
    getNow: function() {
      const today = new Date();
      const date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
      const time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
      const dateTime = date + ' ' + time;
      this.timestamp = dateTime;
    }
  }
});
Run Code Online (Sandbox Code Playgroud)