dcloudio / uni-app

A cross-platform framework using Vue.js
https://uniapp.dcloud.io
Apache License 2.0
40k stars 3.63k forks source link

vue3+uniapp+vite+ts项目中使用 customRef时input 输入框双向绑定失效? #4291

Open likailun101929 opened 1 year ago

likailun101929 commented 1 year ago

问题描述 通过customRef 实现数字输入框 最多输入两位小数 vue3+uniapp+vite+ts项目中使用 customRef时input 输入框双向绑定失效!!! 输入显示还是改动之前的数据

复现步骤

<script setup lang="ts">
  function useNumberRef(value) {
    return customRef((track, trigger) => {
      return {
        get() {
          track()
          return value
        },
        set(newValue) {
          let val = newValue || ''
          val = val.replace(/(^\s*)|(\s*$)/g, '')
          if (!val) {
            value = ''
            trigger()
            return value
          }
          val = val.replace(/^0{2,}.*/g, 0)
          val = val.replace(/^0([1,2,3,4,5,6,7,8,9])/g, '$1')
          val = val.replace(/[^\d.]/g, '')
          val = val.replace(/^\./g, '')
          val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
          val = val.replace(/^(\-)*(\d+)\.(\d{2}).*$/, '$1$2.$3')
          value = val
          trigger()
          return value
        },
      }
    })
  }
  const amount = useNumberRef(null)
</script>
<template>
  <view class="recharge">
    <uni-forms>
      <uni-forms-item label="充值数量" name="amount">
        <uni-easyinput type="digit" v-model="amount" placeholder="请输入" />
      </uni-forms-item>
      <!-- <uni-forms-item label="实时金价">
        {{ goldPrice }}
      </uni-forms-item> -->
      <!-- <uni-forms-item label="支付金额"> {{ payMoeny }} </uni-forms-item> -->
    </uni-forms>
    {{ amount }}
  </view>
</template>

预期结果 输入框能双向绑定

实际结果 image

系统信息:

StrivingRabbit commented 1 year ago

只使用 input 是否正常?能触发 get 或者 set 吗?

likailun101929 commented 1 year ago

只使用input是不是正常?能触发get或者set吗?

能触发 就是输入框回显不对 就像是双向绑定失效一样;因为我处理了最多显示两位小数,所以输入框应该也显示1.33 结果显示了1.33333333

StrivingRabbit commented 1 year ago

能触发,那在 set 中处理过后的数据是否符合预期?

likailun101929 commented 1 year ago

能触发,那在set中处理过后的数据是否符合预期?

image 这张图打印的set get 的值 都是正常的 image 这张图是其他地方使用这个变量 也是符合预期的

就是输入框的显示有问题 我输入多少就显示多少

likailun101929 commented 1 year ago

能触发,那在 set 中处理过后的数据是否符合预期? image 这是vue 中的表现 主要代码是一样的

0131LWG commented 1 year ago

相同的问题,蹲一个解决方案

Sharang-heng commented 2 months ago

相同问题