ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

基于Element ui 实现输入框只能输入数字并支持千分位

2021-06-30 19:30:53  阅读:191  来源: 互联网

标签:const money 千分 value Element 输入框 input replace 光标


实现效果

在这里插入图片描述

设置子组件

<template>
    <el-input
      ref="money"
      v-model.trim="money"
      :placeholder="placeholder"
      v-bind="$attrs"
      v-on="$listeners"
      @input="formatNumber(money,'money')"
      @keyup.enter.native="moneyChange()"
      @blur="moneyChange()"
    >
    <template slot="append">人</template>
    </el-input>
</template>

<script>
export default {
  name: 'MoneyInput',
  props: {
    value: {
      type: null,
      required: true
    },
    placeholder: {
      type: String,
      default: '请输入金额'
    },
    enterFuc: {
      type: Function,
      default: () => {}
    },
    data: {
      type: null,
      default: null
    },
    template: {  //是否展示单位
      type: String,
      default: ''
    }
  },
  data() {
    return {
      money: this.value,
     
    }
  },
  watch: {
    value(newValue, oldValue) {
      this.money = newValue
      this.formatNumber(this.money, 'money')
    }
  },
  mounted() {
    this.formatNumber(this.money, 'money')
  },
  methods: {
    fmresource(s) {
      if (s === '' || s === null || s === '.00' || s === undefined) {
        return ''
      }
      if (s === '-') {
        return '-'
      }
      var lose = ''// 负号
      if (s < 0) { // 判断是否是负数
        s = (s + '').substring(1)// 截取-号
        lose = '-'
      }
      s = s + ''
      // n = n > 0 && n <= 20 ? n : 2;.toFixed(n)
      // s = parseFloat((s + "").replace(/^[^\d.-]/g, "")) + "";
      var l = s.split('.')[0].split('').reverse(); var r = ''; var t = ''
      if (s.indexOf('.') > -1) {
        if (s.split('.')[1] !== null && s.split('.')[1] !== undefined) {
          if (s.split('.')[1].length > 2) {
            s = Number(s).toFixed(2)
          }
          r = ('.' + s.split('.')[1])
        } else {
          r = ''
        }
      }
      for (let i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 === 0 && (i + 1) !== l.length ? ',' : '')
      }
      return lose + '' + t.split('').reverse().join('') + r// 拼接
    },
    formatNumber(value, name) {
      this.$emit('update:data', value)
      value = value + ''
      // 获取input的dom对象,这里因为用的是element ui的input,所以需要这样拿到
      const input = this.$refs[name].$el.getElementsByTagName('input')[0]
      // 获取当前光标的位置
      const cursorIndex = input.selectionStart
      // 字符串中光标之前-的个数
      const lineNumOfCursorLeft = (value.slice(0, cursorIndex).match(/,/g) || []).length
      // 去掉所有,的字符串
      const noLine = value.replace(/,/g, '')
      // 重新格式化
      const newvalue = this.fmresource(noLine.replace(/[^\d\.-]/g, ''))
      // .replace(/(\d{4})/g, '$1 ').replace(/ $/, '')
      // 改后字符串中原光标之前,的个数
      const newLineNumOfCursorLeft = (newvalue.slice(0, cursorIndex).match(/,/g) || []).length
      // 光标在改后字符串中应在的位置
      const newCursorIndex = cursorIndex + newLineNumOfCursorLeft - lineNumOfCursorLeft
      // 赋新值,nextTick保证-不能手动输入或删除,只能按照规则自动填入
      this.$nextTick(() => {
        this.money = newvalue
        // 修正光标位置,nextTick保证在渲染新值后定位光标
        this.$nextTick(() => {
        // selectionStart、selectionEnd分别代表选择一段文本时的开头和结尾位置
          input.selectionStart = newCursorIndex
          input.selectionEnd = newCursorIndex
        })
      })
    },
    moneyChange() {
      const v = this.money ? (this.money + '').replace(/,/g, '').replace(new RegExp(/(\d+)(\.)(\d*)(\2*)(\d*)/g), '$1$2$3$5') : 0
      const money = Object.is(Number(v), NaN) ? 0 : Number(v)
      this.$emit('input', money)
      this.enterFuc()
    }

  }
}
</script>

在父组件引入

引入组件
import MoneyInput from “./compontents/index”

components: {
    MoneyInput
  },

使用

<Money-input v-model.trim="project.hospitalnumber"  template="append" style="width: 100%"></Money-input>

标签:const,money,千分,value,Element,输入框,input,replace,光标
来源: https://blog.csdn.net/weixin_44694682/article/details/118367654

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有