渲染列表 (五) -时间格式处理-dayjs插件更轻量——设置相对时间格式relativeTime 和 i18n国际化中文转换:zh-cn

时间格式处理-dayjs插件更轻量——设置相对时间格式relativeTime 和 i18n国际化中文转换:zh-cn

第一步:打开npm官网,进行搜索 dayjs

第二步:选择第一个 dayjs,进入后选择 简体中文

https://github.com/iamkun/dayjs/blob/HEAD/docs/zh-cn/README.zh-CN.md

第三步:命令行安装包

npm install dayjs --save

第四步:按需进行使用

  • 封装一个相对时间函数

    src/utils/plugin.js

//导插件包
import dayjs from 'dayjs'
//导相对时间插件
import relativeTime from 'dayjs/plugin/relativeTime'
//导国际化插件i18n
import 'dayjs/locale/zh-cn'
dayjs.extend(relativeTime)

相对时间插件: https://day.js.org/docs/en/plugin/relative-time

国际化插件: https://day.js.org/docs/en/i18n/i18n

src/utils/plugin.js

// dayjs,moment 作用:快捷转换时间格式,dayjs更轻量
// dayjs 默认转换时间格式的功能,依赖插件获取更多功能
const relTime = (strDate) => {
  // 实现获取相对时间逻辑  中文格式  相对时间-距离现在 strDate-字符串格式转时间格式
  return dayjs().locale('zh-cn').from(strDate)
}
  • 注册成过滤器 src/utils/plugin.js
export default {
  install (Vue) {
  //实现需要的东西	
    Vue.prototype.$sleep = $sleep
+   Vue.filter('relTime', relTime)
  }
}

使用: src/vies/home/index.vue

<span>{{article.pubdate|relTime}}</span>

版权声明:本文为weixin_44867717原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。