轉(zhuǎn)換函數(shù)
首先封一個(gè)時(shí)間戳轉(zhuǎn)換函數(shù) time.js
// time.js
var Time = {
//獲取當(dāng)前時(shí)間戳
getUnix: function () {
var date = new Date();
return date.getTime();
},
//獲取今天0點(diǎn)0分0秒的時(shí)間戳
getTodayUnix: function () {
var date = new Date();
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date.getTime();
},
//獲取今年1月1日0點(diǎn)0分0秒的時(shí)間戳
getYearUnix: function () {
var date = new Date();
date.setMonth(0);
date.setDate(1);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date.getTime();
},
//獲取標(biāo)準(zhǔn)年月日
getLastDate: function (time) {
var date = new Date(time);
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;
},
//轉(zhuǎn)換時(shí)間
getFormatTime: function (timestamp) {
var now = this.getUnix(); // 當(dāng)前時(shí)間戳
var today = this.getTodayUnix(); // 今天0點(diǎn)的時(shí)間戳
var year = this.getYearUnix(); // 今年0點(diǎn)的時(shí)間戳
var timer = (now - timestamp) / 1000; // 轉(zhuǎn)換為秒級(jí)時(shí)間戳
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 / 3600) + '小時(shí)前';
} else if (timer / 86400 <= 31) {
tip = Math.ceil(timer / 86400) + '天前';
} else {
tip = this.getLastDate(timestamp);
}
return tip;
}
}
module.exports = Time;
使用指令
官方文檔 自定義指令
- 全局指令
// main.js (入口文件)
// 引入Time(自行替換相對(duì)路徑)
import Time from '../static/time';
// 注冊(cè)一個(gè)全局自定義指令 `v-time`
Vue.directive('time', {
// 指令所在組件的 VNode 及其子 VNode 全部更新后調(diào)用
componentUpdated: function (el, binding) {
el.innerHTML = Time.getFormatTime(binding.value);
el.__timeout__ = el.innerHTML = Time.getFormatTime(binding.value);
}
})
// index.vue
// 轉(zhuǎn)換時(shí)間戳變量 createTime
<div v-time="createTime"></div>
- 局部指令
// index.vue
// ...
<div v-time="createTime"></div>
// ...
// 引入Time(自行替換相對(duì)路徑)
import Time from '../static/time';
// ...
directives: {
time: {
componentUpdated: function (el, binding) {
el.innerHTML = Time.getFormatTime(binding.value);
el.__timeout__ = el.innerHTML = Time.getFormatTime(binding.value);
}
}
}
使用過(guò)濾器
官方文檔 過(guò)濾器
- 全局過(guò)濾器
// main.js (入口文件)
// 引入Time (自行替換相對(duì)路徑)
import Time from '../static/time';
// 注冊(cè)一個(gè)全局過(guò)濾器 `formatTime`
Vue.filter('formatTime', function (value) {
if (!value) return '';
return Time.getFormatTime(value);
})
// index.vue
// 轉(zhuǎn)換時(shí)間戳變量 createTime
<div v-time="createTime">{{ createTime | formatTime }}</div>
- 局部過(guò)濾器
// index.vue
// ...
<div v-time="createTime">{{ createTime | formatTime }}</div>
// ...
// 引入Time(自行替換相對(duì)路徑)
import Time from '../static/time';
// ...
filters: {
formatTime: function (value) {
if (!value) return '';
return Time.getFormatTime(value);
}
}