封装moment.js过滤器,及其使用

首先封装一个过滤器

import Vue from "vue"
import moment from "moment"
import "moment-precise-range-plugin"

moment.prototype.preciseDiff = function(d2, returnValueObject) {
  let result = moment.preciseDiff(this, d2, returnValueObject)

  if (!returnValueObject) {
    result = result
      .replace(
        /year(s)?|month(s)?|day(s)?|hour(s)?|minute(s)?|second(s)?/g,
        function(v) {
          if (/year(s)?/.test(v)) {
            return "年"
          }
          if (/month(s)?/.test(v)) {
            return "月"
          }
          if (/day(s)?/.test(v)) {
            return "日"
          }
          if (/hour(s)?/.test(v)) {
            return "小时"
          }
          if (/minute(s)?/.test(v)) {
            return "分"
          }
          if (/second(s)?/.test(v)) {
            return "秒"
          }

          return ""
        }
      )
      .replace(/\s+/g, "")
  }

  return result
}

Vue.prototype.$moment = moment
Vue.prototype.$formatDate = function(time, format = "default", match) {
  const formatTypes = {
    "cn-time-m": "YYYY年MM月DD日, HH时mm分",
    "cn-time-s": "YYYY年MM月DD日, HH时mm分ss秒",
    "cn-time": "YYYY年MM月DD日, HH时mm分ss秒",
    "cn-date": "YYYY年MM月DD日",
    cn: "YYYY年MM月DD日, HH时mm分ss秒",
    default: "YYYY-MM-DD, HH:mm:ss"
  }

  return moment(time, match).format(formatTypes[format])
}

export const formatDate = (time, format = "YYYY-MM-DD, HH:mm:ss", match) => {
  if (!time) {
    return ""
  }

  return moment(time, match).format(format)
}

然后注册,最后在页面中使用
封装moment.js过滤器,及其使用_第1张图片
最后在方法里面使用一下即可
封装moment.js过滤器,及其使用_第2张图片

你可能感兴趣的:(element,vue)