
1.Vue显示实时时间
实时显示时间,代码如下:
<div id="app">{{date}}</div>
<script>
var app=new Vue({
el:"#app",
data:{
date:new Date()
},
mounted:function(){
var _this=this;
this.timer=setInterval(function(){
_this.date=new Date();
},1000);
}
});
</script>
这段代码的功能是在页面中显示实时的当前时间。给定的 HTML 页面中,有一个包含 date
的 div 元素,并且使用 Vue.js 对其进行数据绑定,即将实时时间保存在 date
属性中,并在页面上呈现出来。
在 Vue 实例对象中:
-
el
选项表明 Vue 实例对象要掌管整个页面的哪个 DOM 元素。在本例中,Vue 实例对象掌管的元素是 id 为app
的 div 元素。因此,Vue 实例对象将会在该元素下渲染视图。 -
data
选项用于存储数据属性。在本例中,date
属性指向一个 Date 对象,初始值为当前时间。 -
mounted
生命周期钩子函数表示 Vue 实例对象挂载到了页面上。在本例中,我们在mounted
钩子函数中定义了一个变量_this
来保存 Vue 实例对象this
的引用,以备后用。然后,使用setInterval
函数每隔一秒便更新一次时间,并且把结果保存到date
属性中。
其中几行代码作用如下:
-
var _this=this;
:因为在回调函数中this的指向会改变,所以在mounted函数中缓存Vue实例的this。 -
this.timer=setInterval(function(){},1000);
:使用setInterval()函数循环执行一个函数,每隔一秒就会更新一次当前时间,并将其赋值给Vue实例中的date属性。 -
_this.date=new Date();
:更新Vue实例中的date属性为当前时间。
上述代码,并不能格式化显示时间,修改代码,使时间能够格式化输出,代码如下:
<body>
<div id="app">{{formattedDate}}</div>
<script>
var app=new Vue({
el:"#app",
data:{
date:new Date()
},
mounted:function(){
var _this=this;
this.timer=setInterval(function(){
_this.date=new Date();
},1000);
},
computed: {
formattedDate: function() {
var date = this.date;
var year = date.getFullYear();
var month = (date.getMonth() + 1).toString().padStart(2, '0');
var day = date.getDate().toString().padStart(2, '0');
var hours = date.getHours().toString().padStart(2, '0');
var minutes = date.getMinutes().toString().padStart(2, '0');
var seconds = date.getSeconds().toString().padStart(2, '0');
return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
}
}
});
</script>
</body>
在修改的代码中,添加了一个 computed 属性 formattedDate
,用于格式化日期和时间。在 formattedDate
中,使用 getFullYear()
、getMonth()
、getDate()
、getHours()
、getMinutes()
和 getSeconds()
方法获取对应的日期和时间信息,并使用 padStart() 方法补齐位数,最后用字符串拼接的方式将它们组合成所需的日期时间格式。然后,在页面中把 {{date}}
替换为 {{formattedDate}}
,以显示格式化后的时间。
为什么要把{{date}} 替换为 {{formattedDate}},可以不修改吗,答案是不行的,
需要把 {{date}}
替换成 {{formattedDate}}
,因为在修改后的代码中,已经使用 formattedDate
属性格式化了时间,并将其存储在 formattedDate
中。
如果不把 {{date}}
替换成 {{formattedDate}}
,页面上的时间仍然会显示为未格式化的日期和时间,而不是我们希望的格式化后的日期时间。
因此,为了能够在页面上正确地显示格式化后的时间,必须把 {{date}}
替换成 {{formattedDate}}
。
如果想要在页面上呈现“现在是多少年多少月多少号几点几分”的格式,只需更改 formattedDate
函数中的返回语句即可,需要修改的代码如下:
//return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
return '现在是' + year + '年'+month +'月'+ day +'号'+ hours + '点' + minutes + '分';
修改后就能呈现如下效果:
更多推荐
所有评论(0)