希望如下效果(时间按秒钟更新)
导入Vue依赖的CDN
<script src="https://unpkg.com/vue/dist/vue.min.js"> </script>
创建视图
<div id="app">{{date}}</div>
Model
<script>var app = new Vue({el: "app",data: {date: new Date(); // 初始化date}mounted: function () {var _this = this;this.timer = setInterval(function() {_this.date = new Date(); // 每隔1秒钟更新一次date}, 1000);},beforeDestroy: function () { // 清除定时器if (this.timer) {clearInterval(this.timer);}}
})
</script>
总代码
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="app">{{date}}
</div><script src="https://unpkg.com/vue/dist/vue.min.js"></script><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);},beforeDestroy: function () {if (this.timer) {clearInterval(this.timer);}}})</script>
</body>
</html>
你可能觉得上面的时间看着别扭.
你真正需要的可能是下面这样
那么接下来,我们需要一个formatDate函数.用于将日期转化成需要的格式
// 首先编写一个padDate函数,用于将小于0的数,转换成0a的形式
var padDate = function (value){return value < 10? "0" + value : value
}
// 下面编写formatDate函数. 用于转换日期格式
var formatDate = function(value) {var date = new Date(value);var year = date.getFullYear(); // 获取年份var month = padDate(date.getMonth()+1); // js里面月份(0~11月)会比正常的少1; 使用padDate函数转换小于10的月份var day = padDate(date.getDate());var hours = padDate(date.getHours());var minutes = padDate(date.getMinutes());var seconds = padDate(date.getSeconds());return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
}
使用filters 对{{}}中的参数进行过滤(用上面定义的formatDate)
// HTML
<div id = "app"> {{ date | formatDate}}
</div>// javascript
var app = new Vue({el: '#app',data:{date: new Date();},filters: {formateDate: formatDate // 注意此处没有括号,代表函数赋值}
// ps: 过滤的实质是在date显示之前,先作为参数传给formatDate函数进行处理
全部代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body><div id="app">{{ date | formatDate }}
</div><script src="https://unpkg.com/vue/dist/vue.min.js"></script><script>var padDate = function (value) {return value < 10 ? '0' + value : value;};var formatDate = function (value) { // 这里的value就是需要过滤的数据var date = new Date(value);var year = date.getFullYear();var month = padDate(date.getMonth() + 1);var day = padDate(date.getDate());var hours = padDate(date.getHours());var minutes = padDate(date.getMinutes());var seconds = padDate(date.getSeconds());return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;}var app = new Vue({el: '#app',data:{date: new Date()},filters: {formatDate:formatDate},mounted: function () {var _this = this;this.timer = setInterval(function() {_this.date = new Date();}, 1000);},beforeDestroy: function (){if(this.timer) {clearInterval(this.timer);}}})</script></body>
</html>
参考 《Vue.js实战》 P12