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

Javascript 如何在不刷新vue.js中的页面的情况下更新当前时间戳?,javascript,vue.js,vuejs2,vue-component,Javascript,Vue.js,Vuejs2,Vue Component,在我的vue应用程序中,我使用一种方法来获取当前时间戳,我获取当前时间和日期,但它仅在刷新页面后更新,我希望它在不刷新页面的情况下动态更新 我想我需要包括一些东西,比如设置间隔,但不确定如何实现 <html> <head> <title>VueJs Introduction</title> <script type = "text/javascript" src = "https://cdnjs.cloudfla

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

我想我需要包括一些东西,比如设置间隔,但不确定如何实现

<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>

VueJs简介
{{timestamp}}
var vue_det=新的vue({
el:“#简介”,
数据:{
时间戳:“”
},
创建(){
这个.getNow();
},
方法:{
getNow:function(){
const today=新日期();
const date=today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
const time=today.getHours()+“:“+today.getMinutes()+”:“+today.getSeconds();
const dateTime=日期+''+时间;
this.timestamp=日期时间;
}
}
});

您只调用
this.getNow()
一次
setInterval
可以工作,我想您可以将其设置为1000ms,如下所示:

let vue_det = new Vue({
  el: '#intro',
  data: {
    timestamp: ''
  },
  mounted: function () {
    setInterval(function () {
      this.getNow()
    }.bind(this), 1000)
  }
});
或者在更好的ES6中:

setInterval(() => { this.getNow() }, 1000)

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

setInterval(() => {
  this.getNow();
}, 1000)
完整示例
var-vue\u-det=新的vue({
el:“#简介”,
数据:{
时间戳:“”
},
创建(){
设置间隔(()=>{
这个.getNow();
}, 1000)
},
方法:{
getNow:function(){
const today=新日期();
const date=today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
const time=today.getHours()+“:“+today.getMinutes()+”:“+today.getSeconds();
const dateTime=日期+''+时间;
this.timestamp=日期时间;
}
}
});

VueJs简介
{{timestamp}}
无法将
()=>{this.getNow()}
压缩为
this.getNow