util.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. /**
  2. * 时间戳
  3. * @param {*} timestamp 时间戳
  4. */
  5. const timestampToTime = (timestamp) => {
  6. const date = new Date(timestamp) // 时间戳为10位需*1000,时间戳为13位的话不需乘1000
  7. const Y = date.getFullYear() + '-'
  8. const M =
  9. (date.getMonth() + 1 < 10
  10. ? '0' + (date.getMonth() + 1)
  11. : date.getMonth() + 1) + '-'
  12. const D =
  13. (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
  14. const h =
  15. (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
  16. const m =
  17. (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) +
  18. ':'
  19. const s =
  20. date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  21. return Y + M + D + h + m + s
  22. }
  23. /**
  24. * 存储localStorage
  25. */
  26. const setStore = (name, content) => {
  27. if (!name) return
  28. if (typeof content !== 'string') {
  29. content = JSON.stringify(content)
  30. }
  31. window.localStorage.setItem(name, content)
  32. }
  33. /**
  34. * 获取localStorage
  35. */
  36. const getStore = name => {
  37. if (!name) return
  38. return window.localStorage.getItem(name)
  39. }
  40. /**
  41. * 删除localStorage
  42. */
  43. const removeStore = name => {
  44. if (!name) return
  45. window.localStorage.removeItem(name)
  46. }
  47. /**
  48. * 设置cookie
  49. **/
  50. function setCookie(name, value, day) {
  51. const date = new Date()
  52. date.setDate(date.getDate() + day)
  53. document.cookie = name + '=' + value + ';expires=' + date
  54. }
  55. /**
  56. * 获取cookie
  57. **/
  58. function getCookie(name) {
  59. const reg = RegExp(name + '=([^;]+)')
  60. const arr = document.cookie.match(reg)
  61. if (arr) {
  62. return arr[1]
  63. } else {
  64. return ''
  65. }
  66. }
  67. /**
  68. * 删除cookie
  69. **/
  70. function delCookie(name) {
  71. setCookie(name, null, -1)
  72. }
  73. const validFormAndInvoke = (formEl, success, message = '信息有误', fail = function() {
  74. }) => {
  75. if (!formEl) {
  76. return
  77. }
  78. formEl.validate(valid => {
  79. if (valid) { // form valid succeed
  80. // do success function
  81. success()
  82. // reset fields
  83. formEl.resetFields()
  84. } else { // form valid fail
  85. Vue.prototype.$notify({
  86. title: 'Tips',
  87. message: message,
  88. type: 'error',
  89. duration: 2000
  90. })
  91. // do something when fail
  92. fail()
  93. return false
  94. }
  95. })
  96. }
  97. /**
  98. * 导出
  99. **/
  100. export {
  101. timestampToTime,
  102. setStore,
  103. getStore,
  104. removeStore,
  105. setCookie,
  106. getCookie,
  107. delCookie,
  108. validFormAndInvoke
  109. }