<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<title>vue时间格式化</title>
</head>
<body>
<div id="myApp">
{{date | formatDate}}
</div>
<script>
//在月份、日期、小时等小于10时前面补0
var padDate = function (value) {
return value < 10 ? '0' + value : value;
}
var app = new Vue({
el: '#myApp',
data: {
date: new Date()
},
filters: {
formatDate: function (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;
}
},
mounted: function(){
var _this = this;//声明一个变量指向Vue实例的this,保证作用域一致
this.timer = setInterval(function(){
_this.date = new Date();//修改数据date
}, 1000);
},
beforeDestroy: function(){
if(this.timer){
clearInterval(this.timer);//Vue实例清除前,销毁定时器
}
}
});
</script>
</body>
</html>
Vue 中对时间进行格式化处理,常用方法封装使用;打印结果:2019-10-10 06:10:10
本文介绍了一种在Vue中实现时间格式化的实用方法,通过自定义过滤器将日期对象转换为指定格式的字符串,如'2019-10-10 06:10:10'。该方法利用了JavaScript的Date对象和定时器来实时更新时间显示。
3591

被折叠的 条评论
为什么被折叠?



