vue2 el-input-number 千分位显示的支持(不影响v-model的数值取值)

发布时间 2023-10-23 15:05:59作者: 小白咚
<!-- 增加v-thousands指令 -->
<el-input-number
    v-model="row.money"
    v-thousands
    :controls="false"
    :min="0"
    :precision="2"
    style="width: 100%"

  

// 添加全局指令或局部指令
    directives: {
      thousands: {
        inserted: function (el) {
          // 获取input节点
          if (el.tagName.toLocaleUpperCase() !== 'INPUT') {
            el = el.getElementsByTagName('input')[0]
          }
 
          // 初始化时,格式化值为千分位
          const numberValue = parseFloat(el.value.replace(/,/g, ''))
          if (!isNaN(numberValue)) {
            el.value = numberValue.toLocaleString('zh', {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })
          }
 
          // 聚焦时转化为数字格式(去除千分位)
          el.onfocus = () => {
            el.value = parseFloat(el.value.replace(/,/g, '')).toFixed(2)
          }
 
          // 失去焦点时转化为千分位
          el.onblur = () => {
            const onBlurValue = parseFloat(el.value.replace(/,/g, ''))
            if (!isNaN(onBlurValue)) {
              el.value = onBlurValue.toLocaleString('zh', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2,
              })
            }
          }
        },
      },
    },

  

实现效果为获取焦点时显示数值,失去焦点显示千分位,获取v-model绑定的值为数值。如果想设置数值靠右显示,添加局部css:

<style lang="scss" scoped>
  ::v-deep .el-input-number .el-input__inner {
    text-align: right;
  }
</style>