vue.js--实现实时时间
记录一下这烧脑的瞬间
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>实时显示的日期和时间</title>
<script src="../JS/vue.js"></script>
</head>
<body>
<div id="box">
{{nowdate | formatDate}}
</div>
<script type="text/javascript">
var formatNum = function(num){
return num < 10 ? "0" + num : num;//为数字前添加前导0
}
var demo = new Vue({
el : '#box',
data : {
nowdate : new Date()
},
filters : {
formatDate : function(value){
var year = value.getFullYear();
var month = formatNum(value.getMonth() + 1);
var date = formatNum(value.getDate());
var hour = formatNum(value.getHours());
var minute = formatNum(value.getMinutes());
var second = formatNum(value.getSeconds());
return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second;
}
},
//DOM文档渲染完毕后调用
mounted : function(){
var _this = this;
var timer = setInterval(function(){
_this.nowdate = new Date()//修改数据
},1000);
},
//实例销毁之前调用
beforeDestroy : function(){
if(this.timer){
clearInterval(this.timer); //在Vue实例销毁前清除定时器
}
}
});
</script>
</body>
</html>