美文网首页
vue自定义管道

vue自定义管道

作者: 前端路上的小兵 | 来源:发表于2019-02-19 23:01 被阅读0次
1、创建一个管道——货币过滤管道
>/currency.js

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

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
}
2、调用管道文件在项目中引入
>/main.js
/*
    Vue.filter('currency', currency)
*/
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import store from './store/store'
import { currency } from './currency'

Vue.config.productionTip = false

Vue.filter('currency', currency)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  components: { App },
  template: '<App/>',
  store
})
3、使用管道
<ul>
    <li v-for="product in products" :key="product.title">
        {{ product.title }} - {{ product.price | currency }} x {{ product.quantity }}
    </li>
</ul>

相关文章

  • vue自定义管道

    1、创建一个管道——货币过滤管道 2、调用管道文件在项目中引入 3、使用管道

  • Vue自定义管道,时间过滤器

    1、在src文件夹中创建一个新的文件,用来放置自定义的管道:pipe-vue.js 2、在main.js文件中引入...

  • Vue管道

    在Vue2.x版本中,filter需要自己定义才能够使用 过滤器可以用在两个地方: 双花括号插值,如:{{ mes...

  • Vue.js 模板语法笔记五

    Vue.js 自定义过滤器用作一些常见的文本格式化。由"管道符"指示, 格式如下: