vue货币格式化组件、局部过滤功能以及全局过滤功能

一、在这里介绍一个vue的时间格式化插件: moment 

使用方法: 
1.npm install moment --save2.

  2 定义时间格式化全局过滤器

  在main.js中 导入组件

  import moment from 'moment'

  Vue.filter('dateformat', function(dataStr, pattern = 'YYYY-MM-DD HH:mm:ss') {
      return moment(dataStr).format(pattern)

  })

  filter两个参数 第一个是函数名  第二个是时间格式化处理的函数

3 只需要在需要格式化时间的地方使用插值表达式就OK了

  <!-- 子标题 -->
      <p class="subtitle">
          <span>发表时间:{{ newsinfo.add_time | dateformat('YYYY-MM-DD HH:mm:ss')}}</span>
          <span>点击{{ newsinfo.click }}次</span>
     </p>

第二种方法 

引入moment.js

<script>

let moment = require("moment");

export default {

data() {

return {

}

可以直接使用了

if(this.ruleForm2.startTime == '' || this.ruleForm2.startTime == null || this.ruleForm2.startTime == undefined){

this.ruleForm2.startTime = ''

}else {

this.ruleForm2.startTime = moment(this.ruleForm2.startTime).format('YYYY-MM-DD')

}

如果是想要 转化为年月日分秒

this.ruleForm2.startTime = moment(this.ruleForm2.startTime).format('YYYY-MM-DD HH-mm')

</script>

二、货币格式化 

在页面中,例如价格数据,不管是后台传递过来的还是前台计算之后显示在页面上的,一般都只是一个数字没有格式,完整的格式应该是

要实现这个其实很简单,vue的过滤功能就很好的能解决这个问题,什么叫做过滤,就是将元数据进行相应的处理在显示出来。

首先建立一个 js 文件 currency.js

const digitsRE = /(d{3})(?=d)/g

/**
* value  金额
* currency 货币符号
* decimals  保留位数
*/
export function currency (value, currency, decimals) {
  value = parseFloat(value)
  if (!isFinite(value) || (!value && value !== 0)) return ''
  currency = currency != null ? currency : '$'
  decimals = decimals != null ? decimals : 2
  var stringified = Math.abs(value).toFixed(decimals)
  var _int = decimals
    ? stringified.slice(0, -1 - decimals)
    : stringified
  var i = _int.length % 3
  var head = i > 0
    ? (_int.slice(0, i) + (_int.length > 3 ? ',' : ''))
    : ''
  var _float = decimals
    ? stringified.slice(-1 - decimals)
    : ''
  var sign = value < 0 ? '-' : ''
  return sign + currency + head +
    _int.slice(i).replace(digitsRE, '$1,') +
    _float
}

1、局部过滤,全局不使用,在某一个页面使用

引入:

import {currency} from '@/unit/currency';

这个文件是有返回值的,必须这样引入,并且他不是默认抛出的

js中写法:

filters:{
        currency: currency
    },

页面中需要 价格 格式化的地方写法

{{totalPrice | currency('$')}}

2、全局引入,在任何地方都能使用。

在main.js 中导入,并

Vue.filter("currency", currency);

这里 一定不能加 (),加了就成了函数执行了

这样在全局任何地方都可以使用了。

原文地址:https://www.cnblogs.com/haonanZhang/p/8371791.html