适配vue的时间处理插件

因为后台返回的时间数据的不同,我们可以自己设置filters来过滤时间格式,同时也可以用这个插件来设置一个格式化,将数据转换为对应格式

插件的安装

npm i dayjs --save

创建day.js文件进行配置

引入

// 引入
import dayjs from 'dayjs'

// 引入其中的相对时间 例一天前,五秒前
import rTime from 'dayjs/plugin/relativeTime'

// 全局使用中文
dayjs.locale('zh_cn')

进行配置

// 对时间进行格式化
// type为显示的数据类型,以下是 2012-01-12
export function formatTime(data = new Date(), type = 'YYYY-MM-DD') {
return dayjs(data).format(type)
}

// 配置相对时间 例5秒前 1天前 
dayjs.extend(rTime)

//设置相对时间设置
export const relativeTime = value =>{
return dayjs().to(dayjs(value))
}

// 返出两个设置
export default {
formatTime, relativeTime
}

在main.js挂载实例里

// 引入
import { formatTime,relativeTime } from './utils/formate'

// 挂载在原型
Vue.prototype.$formatTime = formatTime;
Vue.prototype.$relativeTime = relativeTime

项目中使用实例

// 组件中调用格式时间
this.$formatTime(new Date(),'YYYY-MM-DD')

将其放在filter的原型上,已更方便使用

// 在main.js里为filter添加
Vue.filter('relativeTime',relativeTime)
Vue.filter('formatTime',formatTime)

// 前一个是命名,后一个是调用的函数

猜你喜欢

转载自blog.csdn.net/hjdjhh/article/details/122416762
今日推荐