gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 22:21:05 24 4
gpt4 key购买 nike

在我的 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>

最佳答案

在创建的钩子(Hook)中添加 1s 的范围时间:

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

完整示例

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;
}
}
});
<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">
</script>
</body>

</html>

关于javascript - 如何在不刷新 vue.js 页面的情况下更新当前时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57289004/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com