1.封装工具类文件
// utils.js
export default{
//时间格式化
dateFormat(time, flag) {
// time 时间戳 单位秒
// flag=1 年-月-日 时-分
// flag=2 年-月-日
// flag=3 刚刚/分钟前/小时前/年-月-日
time = +time * 1000
let date = new Date(time);
let now = new Date().getTime();
let diff = (now - date) / 1000
let year = date.getFullYear();
let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
if (flag == 1) {
return year + "年" + month + "月" + day + "日" + hours + ":" + minutes;
} else if (flag == 2) {
return year + '-' + month + '-' + day;
} else if (flag == 3) {
if (diff < 30) {
return '刚刚'
} else if (diff < 3600) {
return Math.ceil(diff / 60) + '分钟前'
} else if (diff < 3600 * 24) {
return Math.ceil(diff / 3600) + '小时前'
} else {
return year + '-' + month + '-' + day
}
}
}
}
2.全局挂载
// main.js
import App from './App'
import Vue from 'vue'
import tool from '@/utils/utils.js' //引入
App.mpType = 'app'
Vue.prototype.$tool = tool // 挂载
const app = new Vue({
...App,
store
})
app.$mount()
3.页面使用
// this.$tool.dateFormat(time, 1) 可以直接在页面中使用 参数自定皆为必传项
onShow() {
// time 为时间戳 注意是秒!毫秒的话要/1000
this.nowTime = this.$tool.dateFormat(time, 1);
},