<!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">
<title>Document</title>
<script src="Vue.2.6.10.js"></script>
</head>
<body>
<!-- 一般在服务端的存储时间格式是unix时间戳,如1483200000,本实例来实现这样一个自定义指令v-time,将表达式传入的时间戳转换为相对时间 -->
<div id="app1">
<div v-time="timeNow"></div>
<div v-time="timeBefore"></div>
<input type="text" :value="test" @input="changeTest">
<p v-time="test"></p>
<p>{{ test }}</p>
</div>
</body>
<script>
//为了使判断逻辑更简单,统一使用时间戳进行大小判断,声明一个对象Time,将它们都封装在里面
var Time = {
//获取当前时间戳
getUnix:function(){
var date = new Date();
return date.getTime();
},
//获取今天0点0分0秒时间戳
getTodayUnix:function(){
var date = new Date();
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date.getTime();
},
//获取今年一月一日0点0分0秒的时间戳
getYearUnix:function(){
var date = new Date();
date.setMonth(0);
date.setDate(0);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date.getTime()
},
//获取标准的年月日
getLastDate:function(time){
var date = new Date(time);//传入的是unix时间戳
var month = date.getMonth()+1 < 10 ? '0'+ (date.getMonth()+1):date.getMonth()+1;
var day = date.getDate() < 10 ? '0' + (date.getDate()):date.getDate();
return date.getFullYear() + '-' + month + '-' + day;
},
//格式化时间
getFormatTime:function(timestamp){
var now = this.getUnix();//调用这个对象的2这个方法
var today = this.getTodayUnix();//今天0点时间戳
var year = this.getYearUnix();
var timer = (now - timestamp) / 1000;//转换为秒级时间戳
var tip = '';
if(timer <= 0){
tip='刚刚'
}else if(Math.floor(timer/60) <= 0){
tip='刚刚'
}else if(timer < 3600){
tip=Math.floor(timer/60) + '分钟前'
}else if(timer >= 3600 && (timestamp - today >= 0)){
tip=Math.floor(timer/60) + '小时前'
}else if(timer/86400 <= 31){
tip = Math.ceil(timer/86400) + '天前'
}else{
tip=this.getLastDate(timestamp)
};
return tip;
}
};
Vue.directive('time',{
bind:function(el,binding){
console.log(el,binding);
el.innerHTML = Time.getFormatTime(binding.value);
el._timeout_ = setInterval(function(){
el.innerHTML = Time.getFormatTime(binding.value);
},60000)// 每分钟触发一次
},
update:function(el,binding){
el.innerHTML = Time.getFormatTime(binding.value);
},
unbind:function(el){
clearInterval(el._timeout_);
delete el._timeout_;
}
})
// console.log(new Date(1488930695721));
var app1 = new Vue({
el:"#app1",
data:{
timeNow:(new Date()).getTime(),
timeBefore:1488930695721,//为了便于示范这里是一个写死的时间,且这个时间戳是毫秒级的
//如果服务器返回的是秒级,需要乘以1000
test:1488930695721
},
methods: {
changeTest:function(e){
this.test = e.target.value;
}
},
watch: {
test:function(){
console.log(arguments);
}
},
});
</script>
</html>
框起来的部分是被我魔改了一下,为了实现一个输入时间戳执行时间转换的小测试~