vant金额输入框

1.在components中新建文件夹currency,新建index.js

import Currency from './src/currency.vue'
 
Currency.install = function (Vue) {
  Vue.component(Currency.name, Currency)
}
 
export default Currency

2.在currency中新建文件夹src,在src中间currency.vue。写入核心代码

<template>
  <van-field v-model="liveValue" :name="name" :placeholder="placeholder" :disabled="disabled" :readonly="readonly" @focus="handleFocus" @blur="handleBlur" @change.native="handleChange" v-bind="$attrs" @keydown.native="handleKeydown"></van-field>
</template>
 
<script>
import { formatter, unFormatter, numberKeyCodes, decimalKeyCodes, plusKeyCodes, minusKeyCodes, operKeyCodes } from '../../currentcy.js'
export default {
  name: 'Sjjcurrency',
  props: {
    name: 'String',
    value: {
      type: [String, Number],
      default: ''
    },
    format: {
      type: String,
      default: '16|2'
    },
    placeholder: String,
    separator: {
      type: String,
      default: ','
    },
    decimalSymbol: {
      type: String,
      default: '.'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    readonly: {
      type: Boolean,
      default: false
    },
    rounding: {
      type: Boolean,
      default: false
    },
    appendKeyCodes: Array,
    preFormatter: Function
  },
  components: {
    UnInput
  },
  data () {
    return {
      hiddenValue: '', // 合法金额值
      liveValue: '' // 展示值
    }
  },
  created () {
    let userFormatVal = this.value + ''
    if (this.preFormatter) {
      userFormatVal = this.preFormatter(userFormatVal)
    }
    this.liveValue = formatter(userFormatVal + '', this.separator, this.decimalSymbol, this.format, this.integerFormat, this.rounding)
    this.hiddenValue = unFormatter(this.liveValue, this.separator)
  },
  watch: {
    value (val, oldVal) {
      let userFormatVal = this.value + ''
      if (this.preFormatter) {
        userFormatVal = this.preFormatter(userFormatVal)
      }
      this.liveValue = formatter(userFormatVal + '', this.separator, this.decimalSymbol, this.format, this.integerFormat)
      this.hiddenValue = unFormatter(this.liveValue, this.separator)
    }
  },
  methods: {
    focus () {
      let inputInner = this.$el.querySelector('.van-field_control')
      inputInner.focus()
    },
    blur () {
      let inputInner = this.$el.querySelector('.van-field_control')
      inputInner.blur()
    },
    select () {
      let inputInner = this.$el.querySelector('.van-field_control')
      inputInner.select()
    },
    handleFocus (event) {
      this.liveValue = this.hiddenValue
      this.$emit('focus', event)
    },
    handleBlur (event) {
      let userFormatVal = this.liveValue
      if (this.preFormatter) {
        userFormatVal = this.preFormatter(userFormatVal)
      }
      this.liveValue = formatter(userFormatVal + '', this.separator, this.decimalSymbol, this.format, this.integerFormat, this.rounding)
      this.hiddenValue = unFormatter(this.liveValue, this.separator)
      this.$emit('input', this.hiddenValue)
      this.$nextTick(() => {
        this.$emit('blur', event)
      })
    },
    handleChange (val) {
      if (/[\u4e00-\u9fa5]/g.test(val)) { // 非IE,忽略可输入的中文
        val = this.hiddenValue
      }
      let userFormatVal = val
      if (this.preFormatter) {
        userFormatVal = this.preFormatter(val)
      }
      this.liveValue = formatter(userFormatVal + '', this.separator, this.decimalSymbol, this.format, this.integerFormat, this.rounding)
      this.hiddenValue = unFormatter(this.liveValue, this.separator)
      this.$emit('input', this.hiddenValue)
      this.$nextTick(() => {
        this.$emit('change', this.hiddenValue)
      })
    },
    handleKeydown (event) {
      if (this.readonly || this.disabled) {
        return
      }
      let keyCode = event.keyCode
      if (event.shiftKey) {
        keyCode = -9 + '' + keyCode
      }
      if (event.ctrlKey) {
        keyCode = -7 + '' + keyCode
      }
      // 获取光标位置
      let cursurPosition = 0
      let inputInner = this.$el.querySelector('.van-field_control')
      if (inputInner) {
        if (inputInner.selectionStart !== null && inputInner.selectionStart !== undefined) {
          // 非IE、IE11
          cursurPosition = inputInner.selectionStart
        } else {
          // IE10-
          let range = document.selection.createRange()
          range.moveStart('character', -inputInner.val().length)
          cursurPosition = range.text.length
        }
      } else {
        cursurPosition = -1
      }
      keyCode = parseInt(keyCode)
      let allowKeyCodes = [
        ...numberKeyCodes,
        ...decimalKeyCodes,
        ...operKeyCodes,
        ...plusKeyCodes,
        ...minusKeyCodes
      ]
      if (this.appendKeyCodes && this.appendKeyCodes.length) {
        allowKeyCodes = allowKeyCodes.concat(this.appendKeyCodes)
      }
      // let signalKeyCodes = plusKeyCodes.concat(minusKeyCodes)
      if (allowKeyCodes.indexOf(keyCode) < 0 || (this.liveValue.indexOf('.') >= 0 && decimalKeyCodes.indexOf(keyCode) >= 0) || ((this.liveValue.indexOf('+') >= 0 || this.liveValue.indexOf('-') >= 0) && minusKeyCodes.indexOf(keyCode) >= 0) || ((this.liveValue.indexOf('+') >= 0 || this.liveValue.indexOf('-') >= 0) && plusKeyCodes.indexOf(keyCode) >= 0) || (cursurPosition > 0 && plusKeyCodes.concat(minusKeyCodes).indexOf(keyCode) >= 0)) {
        event.preventDefault()
      } else {
        if (cursurPosition === 0 && (plusKeyCodes.indexOf(keyCode) >= 0 || minusKeyCodes.indexOf(keyCode) >= 0)) {
          // if ((this.liveValue.indexOf('-') < 0 && minusKeyCodes.indexOf(keyCode) >= 0) || (this.liveValue.indexOf('+') < 0 && plusKeyCodes.indexOf(keyCode) >= 0)) { // 可输入+
        if ((this.liveValue.indexOf('-') < 0 && minusKeyCodes.indexOf(keyCode) >= 0)) {
            // 不可输入+
          } else {
            event.preventDefault()
          }
        }
      }
    }
  }
}
</script>

3.currentcy.js

import { BigDecimal, RoundingMode } from 'bigdecimal'
export const numberKeyCodes = [44, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105] // 允许的数字键的keyCode
export const decimalKeyCodes = [190, 110] // 小数键的keyCode
export const plusKeyCodes = [107, -9187] // 正号的keyCode 【小键盘+, 187=(配合shift使用)】
export const minusKeyCodes = [109, 189] // 负号的keyCode
export const operKeyCodes = [9, 46, 8, 37, 39, 35, 36, -767, -786] // 操作特殊字符的KeyCode
 
function __getIntDigitLength__ (intDigitStr) {
  let len = {}
  let intLength = ''
  let decimalLength = ''
  intDigitStr = intDigitStr.trim()
  if (intDigitStr && intDigitStr !== '|' && /^(\d*)\|(\d*)$/g.test(intDigitStr)) {
    intLength = RegExp.$1
    decimalLength = RegExp.$2
    len.intLength = intLength
    len.decimalLength = decimalLength
    return len
  } else {
    return false
  }
}
 
function __getStringRegExp__ (str) {
  try {
    if (str && /[\][{}()*+?.\\^$|]/g.test(str)) {
      if (str !== '\\') return '\\' + str
      else return '\\'
    } else return str || ''
  } catch (e) {
    throw new Error('__getStringRegExp__:' + e.message)
  }
}
 
function __removeSeparator__ (value, separator) {
  try {
    // var _me = this
    var separatorRegExp = __getStringRegExp__(separator) || ''
    if (separatorRegExp) {
      var dh = new RegExp(separatorRegExp, 'img')
      if (value && dh.test(value)) {
        return value.replace(dh, '')
      }
    }
    return value || ''
  } catch (e) {
    throw new Error('__removeSeparator__:' + e.message)
  }
}
 
export function formatter (value, separator, decimalSymbol, intDigitStr, isIntegerOnly, rounding) {
  try {
    // let valueValid = false
    var _currencyValue = {
      intLength: '16',
      decimalLength: '2',
      NegativeValue: '',
      intValue: '',
      decimalValue: '',
      formatValue: ''
    }
    value = value + ''
    if (!value || value === '-' || value === '+') {
      return ''
    }
    // var _me = this,
    var separatorRegExp, _value, __decimalLen, __intLen // 整数部分
    var lenObj = __getIntDigitLength__(intDigitStr)
    if (lenObj) {
      _currencyValue.intLength = lenObj.intLength
      _currencyValue.decimalLength = lenObj.decimalLength
    }
    __intLen = parseInt(_currencyValue.intLength, 10)
    __decimalLen = rounding ? parseInt(_currencyValue.decimalLength, 10) + 1 : parseInt(_currencyValue.decimalLength, 10)
 
    // var isNegative = false // 是否负数
    var valArr = /^-([^-]+)$/.exec(value)
    if (valArr) {
      // isNegative = true // 表示是负数
      _currencyValue.NegativeValue = '-'
      value = valArr[1]
    }
 
    if (separator === '') {
      return ''
    }
 
    _value = value // 整数部分
    _currencyValue.decimalValue = '' // 小数部分
    if (value.indexOf('.') > -1) { // 若含有小数点,则处理得到整数部分和小数部分
      _currencyValue.decimalValue = value.substring(value.indexOf('.') + 1)
      _value = value.substring(0, value.indexOf('.'))
    }
    // 若未输入整数部分,则自动取成0----------------------------------------------------
    _value = _value === '' ? '0' : _value
    // _value === '' ? _value = '0' : _value = _value
 
    if (separator !== '') {
      separatorRegExp = __getStringRegExp__(separator)
      _value = __removeSeparator__(_value, separator) // 去分隔符
    }
    if (isNaN(_value) || isNaN(_currencyValue.decimalValue) || isNaN(value)) { // 若不是数字则报错,isNaN('')=false
      return ''
    }
    // modify begin
    if (isIntegerOnly && value.indexOf('.') < 0) { // 纯整数格式化且不含.时,对纯整数进行格式化
      if (_currencyValue.decimalLength !== '') {
        if (_value.length > __decimalLen) {
          _currencyValue.decimalValue = _value.substring(_value.length - __decimalLen)
          _value = _value.substring(0, _value.length - __decimalLen)
        } else {
          var _s = _value
          for (var i = 0; i < (__decimalLen - _value.length); i++) {
            _s = '0' + _s
          }
          _currencyValue.decimalValue = _s
          _value = '0'
        }
      } else {
        _currencyValue.decimalValue = ''
      }
    } else {
      if (_currencyValue.decimalLength !== '') {
        if (_currencyValue.decimalValue.length < __decimalLen) {
          var _d = _currencyValue.decimalValue
          for (var j = 0; j < (__decimalLen - _currencyValue.decimalValue.length); j++) {
            _d += '0'
          }
          _currencyValue.decimalValue = _d
        } else {
          if (_currencyValue.decimalValue.length > __decimalLen) {
            // valueValid = false
          }
          _currencyValue.decimalValue = _currencyValue.decimalValue.substring(0, __decimalLen)
        }
      }
    }
    // modify end
 
    var _intVal = _value
    if (_currencyValue.intLength !== '') { // 若存在整数位的限制
      if (_currencyValue.intLength < _intVal.length) {
        // valueValid = false
      }
      _intVal = _intVal.substring(0, __intLen)
    }
    _currencyValue.intValue = _value = _intVal
    // 整数处理完毕 end
    var _digitpoint = (_currencyValue.decimalValue ? decimalSymbol : '')
    let zeroFilter = (_currencyValue.intValue + '').split('').filter(x => {
      return x !== '0'
    })
    if (zeroFilter.length === 0) { // 输入所有位数都是0的情况,设置后直接返回
      _currencyValue.intValue = '0'
      let zeroFilterDec = (_currencyValue.decimalValue + '').split('').filter(x => {
        return x !== '0'
      })
      // 去掉输入全部为0时的负号
      if (zeroFilterDec.length === 0) {
        _currencyValue.NegativeValue = ''
      }
 
      _currencyValue.formatValue = _currencyValue.NegativeValue + '0' + (_currencyValue.decimalValue !== '' ? (_digitpoint + _currencyValue.decimalValue) : '')
      if (rounding) {
        _currencyValue.formatValue = new BigDecimal(_currencyValue.formatValue).setScale(__decimalLen - 1, RoundingMode.HALF_UP()).toString()
      }
      return _currencyValue.formatValue
    }
    // 处理整数的前缀0
    if (/^0+/g.test(_currencyValue.intValue) && !(/^(0+)$/g.test(_currencyValue.intValue)) && !(/^0$/g.test(_currencyValue.intValue))) {
      _currencyValue.intValue = _currencyValue.intValue.replace(/^0+/, '')
      _value = _intVal = _currencyValue.intValue
    }
 
    if (rounding) {
      let rVal = _value + _digitpoint + _currencyValue.decimalValue
      let roundingVal = new BigDecimal(rVal).setScale(__decimalLen - 1, RoundingMode.HALF_UP()).toString()
      _value = roundingVal.substring(0, roundingVal.indexOf(_digitpoint))
      _currencyValue.decimalValue = roundingVal.substring(roundingVal.indexOf(_digitpoint) + 1)
    }
 
    // 整数部分的分隔符处理开始
    if (separator !== '') {
      _value = _value + separator
      var re = new RegExp('(\\d)(\\d{3}' + separatorRegExp + ')') // 以3个字符串为一组
      while (re.test(_value)) {
        _value = _value.replace(re, '$1' + separator + '$2')
      }
      _value = _value.replace(new RegExp(separatorRegExp + '$'), '') // 去掉末尾的分隔符
    }
    _currencyValue.formatValue = _currencyValue.NegativeValue + _value + (_currencyValue.decimalValue !== '' ? (_digitpoint + _currencyValue.decimalValue) : '')
    if (+_currencyValue.formatValue < 0) {
      // 去除-号
      return _currencyValue.formatValue.substr(1)
    } else {
      return _currencyValue.formatValue
    }
    // return _currencyValue.formatValue
  } catch (e) {
    throw new Error('formatter', e.message)
  }
}
export function unFormatter (value, separator) {
  return (value + '').replace(new RegExp(separator, 'ig'), '')
}

4.然后就是最愉快的代码引入了(代表10位整数6位小数)

<currency v-model="money" :format="10|6" placeholder="请输入内容" />

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/74579.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

接口测试及接口抓包常用的测试工具

接口 接口测试是测试系统组件间接口的一种测试。接口测试主要用于检测外部系统与系统之间以及内部各个子系统之间的交互点。测试的重点是要检查数据的交换&#xff0c;传递和控制管理过程&#xff0c;以及系统间的相互逻辑依赖关系等。 接口测试的重要性 是节省时间前后端不…

SpringCloud微服务之间如何进行用户信息传递(涉及:Gateway、OpenFeign组件)

目录 1、想达到的效果2、用户信息在微服务之间传递的两种途径3、用RuoYi-Cloud为例进行演示说明&#xff08;1&#xff09;网关将用户信息写在请求头中&#xff08;2&#xff09;业务微服务之间通过OpenFeign进行调用&#xff0c;并且将用户信息写在OpenFeign准备的请求头中&am…

Python 基础教程,Python 是什么?

Python 的诞生是极具戏曲性的&#xff0c;据 Guido 自述记载&#xff0c;Python 语言是在圣诞节期间为了打发无聊的时间而开发的&#xff0c;之所以会选择 Python 作为该编程语言的名字&#xff0c;是因为 Guido 是 Monty Python 戏剧团的忠实粉丝。 Python 语言是在 ABC 语言的…

透镜天线的分类、特点及龙伯球透镜天线原理

透镜天线&#xff0c;一种能够通过电磁波&#xff0c;将点源或线源的球面波或柱面波转换为平面波从而获得笔形、扇形或其他形状波束的天线。通过合适设计透镜表面形状和折射率n&#xff0c;调节电磁波的相速以获得辐射口径上的平面波前。透镜天线吸收了许多光信息工程技术&…

lodash常用方法笔记

_.fromPairs(pairs) 与_.toPairs正好相反&#xff1b;这个方法返回一个由键值对pairs构成的对象。 _.fromPairs([[fred, 30], [barney, 40]]); // > { fred: 30, barney: 40 }Object.fromEntries()有同样的功能&#xff0c;只是在高版本浏览器才支持&#xff1a; _toPai…

VR全景智慧文旅,用科技助力旅游业振兴

引言&#xff1a; 近年来&#xff0c;科技的迅猛发展将我们带入一个全新的数字化时代&#xff0c;而虚拟现实&#xff08;Virtual Reality&#xff0c;简称VR&#xff09;技术则以其令人惊叹的全新方式&#xff0c;影响着各个领域。其中&#xff0c;旅游业作为人们探索世界、体…

通过Python爬虫提升网站搜索排名

目录 怎么使用Python爬虫提升排名 1. 抓取竞争对手数据&#xff1a; 2. 关键词研究&#xff1a; 3. 网页内容优化&#xff1a; 4. 内部链接建设&#xff1a; 5. 外部链接建设&#xff1a; 6. 监测和调整&#xff1a; 需要注意哪些方面 1. 合法性和道德性&#xff1a; …

docker容器管理

创建容器&#xff1a; docker run --name 容器名 -d -p 端口1:端口2 –name :是启动容器时&#xff0c;给容器定义的名称&#xff0c;不使用该参数时&#xff0c;容器启动成功之后&#xff0c;会生成随机名称 -d &#xff1a;代表容器处于后台yunx -p &#xff1a;指定容器的端…

stm32项目(10)——基于stm32的盲人监护系统

一.实现的功能 本次设计的盲人监护系统&#xff0c;旨在为盲人的外出提供保护。主要功能如下&#xff1a; 超声波测距模块检测前方障碍物&#xff0c;当前方有障碍物时&#xff0c;语音模块报警提示“前方有障碍物&#xff0c;请绕道”&#xff0c;盲人在听到这条语音后就知…

数据分析案例丨商品零售购物篮分析(上)

购物篮分析关联规则挖掘应用 将单个客户一次购买商品的总和(以收银台结账为准)称为一个购物篮。那么购物篮分析就是针对商品的相关性进行分析。因为最初这种关联分析主要是在超市应用广泛&#xff0c;所以也称为“购物篮分析”。 购物篮分析是商业领域最前沿、最具挑战性的问…

ASP.NET Core - 缓存之分布式缓存

分布式缓存是由多个应用服务器共享的缓存&#xff0c;通常作为访问它的应用服务器的外部服务进行维护。 分布式缓存可以提高 ASP.NET Core 应用的性能和可伸缩性&#xff0c;尤其是当应用由云服务或服务器场托管时。 与其他将缓存数据存储在单个应用服务器上的缓存方案相比&am…

日常BUG——git提交代码报错

&#x1f61c;作 者&#xff1a;是江迪呀✒️本文关键词&#xff1a;日常BUG、BUG、问题分析☀️每日 一言 &#xff1a;存在错误说明你在进步&#xff01; 一、问题描述 git 在提交代码时报错&#xff1a; Committing is not possible because you have unmerge…

智慧工地源码,互联网+建筑工地,基于微服务+Java+Spring Cloud +Vue+UniApp开发

基于微服务JavaSpring Cloud VueUniApp MySql开发的智慧工地云平台源码 智慧工地概念&#xff1a; 智慧工地就是互联网建筑工地&#xff0c;是将互联网的理念和技术引入建筑工地&#xff0c;然后以物联网、移动互联网技术为基础&#xff0c;充分应用BIM、大数据、人工智能、移…

日常BUG—— SpringBoot项目DEBUG模式启动慢、卡死。

&#x1f61c;作 者&#xff1a;是江迪呀✒️本文关键词&#xff1a;日常BUG、BUG、问题分析☀️每日 一言 &#xff1a;存在错误说明你在进步&#xff01; 一、问题描述 我们调试程序时&#xff0c;需要使用DEBUG模式启动SpringBoot项目&#xff0c; 有时候会发…

Blazor简单教程(1.1):Razor基础语法

文章目录 前言基本文件配置引入Layout组件 语法介绍pagecodeRazor 语法[ 显式表达和隐式表达](https://learn.microsoft.com/zh-cn/aspnet/core/mvc/views/razor?viewaspnetcore-7.0#explicit-razor-expressions) 绑定简单绑定双向绑定带参数的函数绑定 依赖注入 前言 Blazor…

【Django】无法从“django.utils.encoding”导入名称“force_text”

整晚处理 Django 的导入错误。 我将把它作为提醒&#xff0c;希望处于相同情况的人数会减少。 原因 某些软件包版本不支持Django 4 请看下表并决定Django和Python的版本 方案 如果出现难以响应&#xff0c;或者更改环境麻烦&#xff0c;请尝试以下操作 例如出现以下错误 …

对方发送的文件已过期如何恢复,这样做很简单

我们常常使用微信来发送文件、传输文件&#xff0c;但很多人也会遇到文件过期的情况。每当发现文件已过期&#xff0c;都会懊恼自己当初为什么没有早点下载保存。 大家要知道&#xff0c;微信文件如果7天内没有及时下载是会被清理的。不过&#xff0c;大家不要着急&#xff0c…

软硬件免费,服务收费:网络安全商业模式正在被颠覆

大数据产业创新服务媒体 ——聚焦数据 改变商业 从元宇宙到造汽车&#xff0c;重回国内A股市场五年的360一路苦追热点。一直到大模型横空出世&#xff0c;360才算真正找到感觉&#xff0c;经历一次战略上的回归。 在8月9日的互联网安全大会上&#xff0c;一袭红衣的红衣教主周…

iTOP-3568开发板使用OpenCV处理图像-颜色转换

本小节代码在配套资料“iTOP-3568 开发板\03_【iTOP-RK3568 开发板】指南教程 \04_OpenCV 开发配套资料\05”目录下&#xff0c;如下图所示&#xff1a; cv2.cvtColor()函数功能&#xff1a; 将一幅图像从一个色彩空间转换到另一个色彩空间。 函数原型&#xff1a; cv2.cvt…

【100天精通python】Day35:一文掌握GUI界面编程基本操作

目录 专栏导读 1 GUI 编程概述 1.1 为什么需要GUI&#xff1f; 1.2 常见的GUI编程工具和库 1.3 GUI应用程序的组成和架构 2 使用Tkinter 库 进行GUI编程 2.1 使用Tkinter库进行GUI编程的基本流程 2.2 使用Tkinter库进行GUI编程 2.2.1 导入Tkinter库 2.2.2 添加标签和…