vue 1 安装插件
npm install dayjs
或
yarn add dayjs
2 将dayjs挂载到全局上
2.1 在 main.js 全局挂载
/**
* 时间格式化过滤器
*/
// 引入dayjs格式化时间
import dayjs from 'dayjs'
// 引入中文包
import 'dayjs/locale/zh-cn'
// 导入相对时间插件
import relativeTime from 'dayjs/plugin/relativeTime'
Vue.use(VueQuillEditor)
// 相对时间使用插件
dayjs.extend(relativeTime)
// 使用中文包
dayjs.locale('zh-cn')
// 将dayjs挂载到全局
Vue.prototype.$dayjs = dayjs
2.2 在组件中进行使用
// 格式化时间
// res.data.items 是获取的文章的数据,是数组
res.data.items.forEach(item => {
// item.createTime 是当前循环到的对象中的时间属性
item.createTime = this.$dayjs(item.createTime).format('YYYY-MM-DD hh:mm:ss')
})
// 再把当前获取回来的数据(数组)并且进行时间过滤后传给在外面定义的数组属性
this.tableData = res.data.items
2.3 前后的效果图对比
过滤前:
过滤后: