In my vue application i am using a method to get current timestamp , i am getting the current time and date but its get updated only after refreshing the page , i want it get updated dynamically without page refresh.
i guess I need to include something like set interval not sure how to implement
<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>
Add range time of 1s in created hook like :
setInterval(() => {
this.getNow();
}, 1000)
Full example
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With