Vue 时间过滤器Filters全局使用

111 阅读1分钟

创建filters>filter.js

/**
 *格式化时间
 *yyyy-MM-dd hh:mm:ss
 */
export function formatDate(time, fmt) {
  if (time === undefined || '') {
    return
  }
  const date = new Date(time)
  console.log(/(y+)/.test(fmt));
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  const o = {
    'M+': date.getMonth() + 1, //月份
    'd+': date.getDate(),  // 日
    'h+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds() // 秒
   // "q+": Math.floor((this.getMonth() + 3) / 3), //季度
   // "S": this.getMilliseconds() //毫秒
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const str = o[k] + ''
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : ('00' + str).substr(str.length))
    }
  }
  return fmt
}

创建filters>index.js

import Vue from "vue";
import * as filter from "./filter";

// 应用于插值表达式中
Object.keys(filter).forEach((k) => Vue.filter(k, filter[k]));

// 应用于方法中
Vue.prototype.$formatDate = Vue.filter("formatDate");

main.js

// filters 过滤器 挂载全局
import './filters'

使用方法

<template>
// 插值表达式中使用
  <div>{{ time | formatDate("yyyy-MM-dd") }}</div>
  //  2023-01-31   格式化后的时间
</template>
export default {
  data () {
      return {
        time:'Tue Jan 31 2023 14:53:12 GMT+0800 (中国标准时间)',
      }
    },
    created() {
    // 方法中使用
      this.$formatDate(this.time,"yyyy-MM-dd")
      //  2023-01-31 格式化后的时间
  },
}