vue全局过滤器常用方法封装,也可单独使用

以前经常在csdn现在觉得掘金的风格我蛮喜欢的就吧自己的文章搬运过来了,可以让自己或者需要的人直接打包带走的那种。?
由于目前开发用的是vue,经常会把一些日常使用的方法封装成一个函数,但是我觉得使用的时候每次还得import还是有些麻烦?,所有现在封装的时候大多直接做成过滤器的形式。看代码吧!!!

1.首先是日常用的最多的缺省数据,当后台返回null、undefined等的时候,前端展示‘–’

const tranNull = value => {
  if (value === null || value === undefined || value === '') return '--'
  return value
}
复制代码

2.同理也能做图片缺省,NoImgUrl你自己引入的哦,图片尺寸完全自己定制

// 列表封面缺省
const defaultImage = (value, width = 150, height = 150) => {
  if (value === null || value === undefined || value === '') return NoImgUrl
  return `${value}_${width}x${height}.jpg`
}
复制代码

3.数字格式化,相信很多人都写过,这版是超过10万以内正常显示,超过十万加上w,超过8位数显示亿,可以直接自己修改?

const tranNumber = (num, point = 2) => {
// point是保留几位小数
  if (num === null || num === undefined || num === '' || num === '--') return '--'
  if (!(num >= 0)) {
    if (!num) {
      return '-'
    }
    return num
  }
  num = num + ''
  const numStr = num.toString()
  const numStrNoPoint = numStr.split('.')[0]
  const len = numStrNoPoint.length
  let decimal
  // 十万以内直接返回
  if (len < 6) {
    return numStr
  } else if (len > 8) {
    // 大于8位数是亿
    decimal = numStrNoPoint.substring(
      numStrNoPoint.length - 8,
      numStrNoPoint.length - 8 + point
    )
    if (decimal.length < 2) {
      decimal = decimal.padEnd(2 - decimal.length, '0')
    }
    return (
      Math.floor(numStrNoPoint / 100000000) + '.' + decimal + '亿'
    )
  } else if (len > 5) {
    // 大于6位数是十万 (以10W分割 10W以下全部显示)
    decimal = numStrNoPoint.substring(
      numStrNoPoint.length - 4,
      numStrNoPoint.length - 4 + point
    )
    if (decimal.length < 2) {
      decimal = decimal.padEnd(2 - decimal.length, '0')
    }
    return Math.floor(numStrNoPoint / 10000) + '.' + decimal + 'w'
  }
}
复制代码

4.相信大家遇到很多金钱前面加“¥”的需求,但是为返回null或者undefined呢?这会让你更简单。?

const RMB = (value) => {
  if (value === '--' || value === null || value === undefined) return value
  return `¥${value}`
}
复制代码

5.毫秒转小时

const formatTimeLine = (value) => {
  if (value && value >= 0) {
    return (value / (60 * 60 * 1000)).toFixed(2) + 'h'
  }
  return '--'
}
复制代码

6.格式化时间为 2020-1-1 格式的

const formatTime =(time, fmt = 'yyyy-MM-dd') =>{
  // time是毫秒
  time = time - 0
  const date = new Date(time)
  const o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + '').substr(4 - RegExp.$1.length)
    )
  for (const 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
}
复制代码

7.数字每三位加个逗号

const toThousands =(num)=> {
    var result = [],
      counter = 0;
    num = (num || 0).toString().split('');
    for (var i = num.length - 1; i >= 0; i--) {
      counter++;
      result.unshift(num[i]);
      if (!(counter % 3) && i != 0) {
        result.unshift(',');
      }
    }
    return result.join('');
  },
// 优雅正则写法
var test = '1234567890'
var format = test.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
console.log(format) // 1,234,567,890
复制代码

因为是全局过滤器我们在最上面引入一下然后最后得注册一下

// 顶部
import Vue from 'vue'
复制代码
// 底部
export default () => {
  Vue.filter('tranNumber', tranNumber)
  Vue.filter('tranNumberPrice', tranNumberPrice)
  Vue.filter('formatTimeLine', formatTimeLine)
  Vue.filter('tranNull', tranNull)
  Vue.filter('defaultImage', defaultImage)
  Vue.filter('RMB', RMB)
  Vue.filter('formatTime', formatTime)
}
复制代码

使用方法直接无需任何引入

// 左侧需要改变的值,右侧过滤
<p>{{value | tranNull}}</p>
复制代码

过滤器就这些了,希望能够帮助到自己和需要帮助的人,以后如果有更好的可以加进去,各位大神也可以私发给我。?

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享