相對時間處理(Dayjs外掛)
阿新 • • 發佈:2021-02-16
技術標籤:npmjavascript
1. 安裝包
npm i dayjs
2. 封裝模組
date-time.js檔案中:
// 提供用來處理日期時間的工具模組
import dayjs from 'dayjs'
// 引入中文語言包
import 'dayjs/locale/zh-cn'
// 引入外掛 dayjs/plugin/relativeTime
// 在你npm i daysj時,外掛已經下載了。
// 具備計算相對時間的功能
import rTime from 'dayjs/plugin/relativeTime'
// 使用中文語言包。固定格式
dayjs.locale('zh-cn')
// 使用外掛。固定格式dayjs.extend(外掛)
dayjs.extend(rTime)
export const relativeTime = function (yourTime) {
// 使用dayjs提供的api對使用者傳入的時間 yourTime
// 進行格式化,以返回一個相對時間
return dayjs().to(dayjs(yourTime))
// console.log(yourTime)
// return dayjs(yourTime).format('DD/MM/YYYY')
}
3. 在main.js中以全域性過濾器的引入
import { relativeTime } from '@/utils/date-time'
// 定義一個全域性過濾器
// relativeTime是在/utils/date-time.js中定義的
+ Vue.filter('relativeTime', relativeTime)
4. 在模組中使用
<span>{{ item.pubdate | relativeTime}}</span>