[英]Getting current time and date in vue.js
I need to get current time and date in the webpage , i am having the javascript code for it .我需要在网页中获取当前时间和日期,我有它的 javascript 代码。 not sure how to Implement in vue.js .I am attaching the code sample here.
不确定如何在 vue.js 中实现。我在此处附上代码示例。
html and plain js code: html和纯js代码:
<html>
<body>
<h2>JavaScript new Date()</h2>
<p id="timestamp"></p>
<script>
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" +
today.getSeconds();
var dateTime = date+' '+time;
document.getElementById("timestamp").innerHTML = dateTime;
</script>
</body>
</html>
i need to implement in vue.js where should i include whether in mounted or computed or method?我需要在 vue.js 中实现,我应该在哪里包括挂载、计算或方法?
Because the time at present isn't depend on any data variable, so we can write it in methods , and call in created因为现在的时间不依赖于任何数据变量,所以我们可以把它写在methods中,然后调用created
Read more about computed and methods here在此处阅读有关计算和方法的更多信息
You can copy and run it in CodingGround您可以在CodingGround中复制并运行它
<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() {
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;
}
}
});
</script>
</body>
</html>
Assuming you have a component, like Dashboard.vue
, you can use a getter:假设您有一个组件,例如
Dashboard.vue
,您可以使用 getter:
<template>
<v-container fluid>
<h1>{{ timestamp }}</h1>
</v-container>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
@Component
export default class Dashboard extends Vue {
get timestamp() {
const today = new Date();
const date = today.getFullYear() + '-' + (today.getMonth()+1) + '-' + today.getDate();
const time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
const timestamp = date + ' ' + time;
return timestamp;
}
}
</script>
I came up with this code in vue js and You can use this way我在 vue js 中提出了这段代码,你可以使用这种方式
var first_time = '09:00:00'
var today = new Date()
var now_date = (today.getFullYear() + '-' + (today.getMonth()+1) + '-' + today.getDate());
var now_time = (today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds()).toString()
if (now_time === first_time){
console.log('true')
}else(){
console.log('false')
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.