javascript - 在 vue.js 中获取当前时间和日期
问题描述
我需要在网页中获取当前时间和日期,我有它的 javascript 代码。不确定如何在 vue.js 中实现。我在此处附上代码示例。
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>
我需要在 vue.js 中实现,我应该在哪里包括挂载、计算或方法?
解决方案
因为现在的时间不依赖于任何数据变量,所以我们可以把它写在methods中,然后调用created
在此处阅读有关计算和方法的更多信息
您可以在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>