vue项目中常见的 filter 过滤器总结

使用方法

import Vue from "vue";

在双花括号中:

{{ message | timeFilter }}
{{message | filterA | filterB}}
{{message | fliterA('arg1',arg2)}}

在 v-bind 简写:中:

<div :id="rawId | timeFilter></div>

//时间戳转换为"yyyy-MM-dd HH:mm:ss"格式

Vue.filter("timeFilter", function (val) {
  var unixtimestamp = new Date(val);
  var year = 1900 + unixtimestamp.getYear();
  var month = "0" + (unixtimestamp.getMonth() + 1);
  var date = "0" + unixtimestamp.getDate();
  var hour = "0" + unixtimestamp.getHours();
  var minute = "0" + unixtimestamp.getMinutes();
  var second = "0" + unixtimestamp.getSeconds();
  return (
    year +
    "-" +
    month.substring(month.length - 2, month.length) +
    "-" +
    date.substring(date.length - 2, date.length) +
    " " +
    hour.substring(hour.length - 2, hour.length) +
    ":" +
    minute.substring(minute.length - 2, minute.length) +
    ":" +
    second.substring(second.length - 2, second.length)
  );
});
Vue.filter("dateTimeFormat", function (date, fmt = 'yyyy-MM-dd HH:mm:ss') { //日期时间格式化 
  if (!date) {
    return ''
  }
  if (typeof date === 'string') {
    date = date.replace('T', ' ').replace('Z', '');
    date = new Date(date.replace(/-/g, '/'))
  }
  if (typeof date === 'number') {
    date = new Date(date)
  }
  var o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
    'H+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'q+': Math.floor((date.getMonth() + 3) / 3),
    'S': date.getMilliseconds()
  }
  var week = {
    '0': '\u65e5',
    '1': '\u4e00',
    '2': '\u4e8c',
    '3': '\u4e09',
    '4': '\u56db',
    '5': '\u4e94',
    '6': '\u516d'
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  if (/(E+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? '\u661f\u671f' : '\u5468') : '') + week[date.getDay() + ''])
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return fmt
});

秒、毫秒转时分秒显示 例:65000 => 00:01:05
参数:isMs 是否是毫秒;dft:默认显示

Vue.filter('timeLongFormat', function (value, isMs = false, dft = '00:00:00') {
  let total = parseInt(value);
  if (!isNaN(total)) {
    if (isMs) {
      total = total / 1000;
    }
    let hours = parseInt(total / 3600);
    let minutes = parseInt((total % 3600) / 60);
    let seconds = parseInt((total % 3600) % 60);
    let h = hours > 9 ? hours : '0' + hours;
    let m = minutes > 9 ? minutes : '0' + minutes;
    let s = seconds > 9 ? seconds : '0' + seconds;
    return h + ':' + m + ':' + s;
  } else {
    return dft;
  }
});

/秒、毫秒(时长)格式化为时分秒(中文)(例:65000ms => 1分5秒)

Vue.filter("timeLongFormat_zh", function (valuevalue, isMs = false, dft = '--') {
  let total = parseInt(value);
  if (!isNaN(total)) {
    if (isMs) {
      total = total / 1000;
    }
    let hours = parseInt(total / 3600);
    let minutes = parseInt((total % 3600) / 60);
    let seconds = parseInt((total % 3600) % 60);
    let h = hours == 0 ? "" : `${hours}时`;
    let m = minutes == 0 ? "" : `${minutes}分`;
    let s = seconds == 0 ? "" : `${seconds}秒`;
    return h + m + s;
  } else {
    return dft;
  }
});
Vue.filter("serviceStatus", function (value) {
  if (value == "1") {
    return "未审核";
  } else if (value == "2") {
    return "已审核";
  } else if (value == "3") {
    return "已完成";
  } else if (value == "5") {
    return "已确认";
  } else if (value == "4") {
    return "已驳回";
  }
});
Vue.filter("statusFilter", function (value) {
  if (value == "UNPAID") {
    return "未支付";
  } else if (value == "PAID") {
    return "已支付";
  } else if (value == "PAYING") {
    return "支付中";
  } else if (value == "ERROR") {
    return "退款";
  }
});

字典表中获取的下拉选项过滤

Vue.filter("codeFilter", function (val, list) {
  list &&
    list.forEach(item => {
      if (item.itemValue == val) {
        val = item.itemName;
      }
    });
  return val;
});

AccessKey-hidden

Vue.filter("accessKeyHiddenFilter", function (val) {
  if (val && val.length == 32) {
    val = val.substring(0, 8) + "****************" + val.substring(25);
  }
  return val;
});

格林时间转换成北京时间

Vue.filter('greenTime', function (time) {
  //时间处理为空
  if (time == null) {
    return "--"
  }
  var unixtimestamp = new Date(time)
  var year = 1900 + unixtimestamp.getYear()
  var month = '0' + (unixtimestamp.getMonth() + 1)
  var date = '0' + unixtimestamp.getDate()
  var hour = '0' + unixtimestamp.getHours()
  var minute = '0' + unixtimestamp.getMinutes()
  var second = '0' + unixtimestamp.getSeconds()
  return (
    year +
    '-' +
    month.substring(month.length - 2, month.length) +
    '-' +
    date.substring(date.length - 2, date.length) +
    ' ' +
    hour.substring(hour.length - 2, hour.length) +
    ':' +
    minute.substring(minute.length - 2, minute.length) +
    ':' +
    second.substring(second.length - 2, second.length)
  )

});

/保留小数

Vue.filter("toFixed", function (val, acc) { //保留小数位,acc为保留几位小数位
  let num = parseFloat(val);
  if (isNaN(num)) {
    num = 0;
  }
  let accuracy = parseInt(acc);
  if (isNaN(accuracy) || accuracy < 0 || accuracy > 10) {
    accuracy = 2;
  }
  return num.toFixed(accuracy);
});

转百分比

Vue.filter("toPercent", function (val, acc) { //小数转百分比 ,acc为保留小数位
  let num = parseFloat(val);
  if (isNaN(num)) {
    num = 0;
  }
  let accuracy = parseInt(acc);
  if (isNaN(accuracy) || accuracy < 0 || accuracy > 10) {
    accuracy = 2;
  }
  return (num * 100).toFixed(accuracy) + "%"
});

byte转K、M、G

Vue.filter("bytesToSize", function (bytes) { //文件大小单位转换
  if (bytes === 0) {
    return '0 B'
  };
  var k = 1024;
  var sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  var i = Math.floor(Math.log(bytes) / Math.log(k));
  return (bytes / Math.pow(k, i)).toPrecision(4) + ' ' + sizes[i];
});

数据源是对象的键值转换

Vue.filter("objectKeyToValueConverter", function (val, keyValueObject) {
  var isExists = _.has(keyValueObject, val);
  if (isExists) {
    return keyValueObject[val];
  }
  return "";
});

重在分享代码,觉得有用,记得点赞收藏,谢谢

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值