效果图如下:
话不多说直接上源码
源代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="../js/vue.js"></script>
</head>
<body>
<div id="box">
现在的时间是:<br />
{{nowdate|formatDate}}
</div>
<script type="text/javascript">
var formatNum = function(num){
return num < 10 ? "0" + num : num
}
var vm = new Vue({
el:"#box",
data:{
nowdate:new Date()
},
filters:{
formatDate(val){
var year = val.getFullYear()
var month = formatNum(val.getMonth() + 1)
var day = formatNum(val.getDate())
var hour = formatNum(val.getHours())
var min = formatNum(val.getMinutes())
var sec = formatNum(val.getSeconds())
return year + "-" + month + "-" + day
+ " " + hour + ":" + min + ":" + sec
}
},
mounted:function(){
var t = this
var timer = setInterval(function(){
t.nowdate = new Date()
},1000)
},
beforeDestroy:function(){
if(this.timer){
clearInterval(this.timer)
}
}
})
</script>
</body>
</html>
注意!!!!
mounted生命周期函数中,用var t = this来中转了一下this对象,因为setInterval里的this.(…)是指window对象,而window对象里没有nowdate属性,所以直接写this.nowdate是不会实现定时器效果的。用var t = this来中转this对象,使得t代表了vue实例对象,vue实例对象里是有nowdate属性。