1.新建filters文件夹,在文件夹新建index.js
export function DateformaDate(value) {
//创建一个时间日期对象
var padaDate = function (value) {
return value < 10 ? "0" + value : value;
};
var date = new Date();
var year = date.getFullYear(); //存储年
var month = padaDate(date.getMonth() + 1); //存储月份
var day = padaDate(date.getDate()); //存储日期
var hours = padaDate(date.getHours()); //存储时
var minutes = padaDate(date.getMinutes()); //存储分
var seconds = padaDate(date.getSeconds()); //存储秒
//返回格式化后的日期
return (
year +
"-" +
month +
"-" +
day +
" " +
hours +
":" +
minutes +
":" +
seconds
);
}
2.在main.js引入
import * as filters from './filters' // global filters
Object.keys(filters).forEach(key => {
Vue.filter(key, filters[key])
})
3.在vue文件中引入
{{ date | DateformaDate }}
data(){
return{
date: new Date(),
}
}
mounted() {
//创建定时器更新时间
var _this = this;
this.timeId = setInterval(function () {
_this.date = new Date();
}, 1000);
},
beforeDestroy: function () {
//实例销毁前青出于定时器
if (this.timeId) {
clearInterval(this.timeId);
}
},
实时获取时间功能实现