index.js 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import baseComponent from '../helpers/baseComponent'
  2. import classNames from '../helpers/classNames'
  3. import { parse, diff, format } from './core/index'
  4. import locales from './locales/index'
  5. baseComponent({
  6. properties: {
  7. prefixCls: {
  8. type: String,
  9. value: 'wux-timeago',
  10. },
  11. to: {
  12. type: null,
  13. value: null,
  14. observer(newVal) {
  15. const { from, lang } = this.data
  16. this.updated(newVal, from, lang)
  17. },
  18. },
  19. from: {
  20. type: null,
  21. value: null,
  22. observer(newVal) {
  23. const { to, lang } = this.data
  24. this.updated(to, newVal, lang)
  25. },
  26. },
  27. refreshable: {
  28. type: Boolean,
  29. value: false,
  30. observer(newVal) {
  31. const { to, from, lang } = this.data
  32. this.updated(to, from, lang, true)
  33. },
  34. },
  35. lang: {
  36. type: String,
  37. value: 'zh_CN',
  38. observer(newVal) {
  39. const { to, from } = this.data
  40. this.updated(to, from, newVal, true)
  41. },
  42. },
  43. },
  44. data: {
  45. currentTo: null,
  46. currentFrom: null,
  47. timeago: null,
  48. },
  49. methods: {
  50. /**
  51. * 更新时间
  52. * @param {Any} currentTo 当前开始时间
  53. * @param {Any} currentFrom 当前截止时间
  54. * @param {String} lang 返回文本的语言,可选值为 en、zh_CN、zh_TW
  55. * @param {Boolean} isForce 是否强制更新
  56. */
  57. updated(currentTo, currentFrom, lang, isForce) {
  58. // clearTimeout
  59. this.clearTimer()
  60. // check datetime
  61. if (currentTo !== this.data.currentTo || currentFrom !== this.data.currentFrom || isForce) {
  62. const diffTime = diff(currentTo, currentFrom)
  63. const timeago = format(diffTime, locales[lang])
  64. this.setData({ currentTo, currentFrom, timeago }, () => {
  65. // check refreshable
  66. if (this.data.refreshable && !this.data.from) {
  67. const howOld = diff(currentTo, currentFrom, 'minute')
  68. const secondsUntilUpdate = howOld < 1 && 1 || howOld < 60 && 30 || howOld < 180 && 300 || 3600
  69. // setTimeout
  70. this.timeout = setTimeout(() => {
  71. this.updated(currentTo, this.getNow(), lang)
  72. }, secondsUntilUpdate * 1000)
  73. }
  74. })
  75. }
  76. },
  77. /**
  78. * 清除定时器
  79. */
  80. clearTimer() {
  81. if (this.timeout) {
  82. clearTimeout(this.timeout)
  83. this.timeout = null
  84. }
  85. },
  86. /**
  87. * 获取当前截止时间
  88. */
  89. getNow() {
  90. const { from } = this.data
  91. return from ? from && parse(from) : new Date()
  92. },
  93. },
  94. detached() {
  95. this.clearTimer()
  96. },
  97. })