uni-app input绑定值为空字符时,动态设置内容为数值0无效

uni-app input绑定值为空字符时,动态设置内容为数值0无效

开发环境 版本号 项目创建方式
Windows w11 HBuilderX

示例代码:

<template>  
    <view>  
        <input class="uni-input" v-model="number" placeholder="自动获得焦点" />  
        Home  
        <button @click="run">Run</button>  
    </view>  
</template>  
<script>  
    export default {  
        data() {  
            return {  
                number:''  
            }  
        },  
        methods: {  
            run(){  
                //当原内容为空字符串(number:'')  
                this.number=0;//无效  

                //当原内容为非空字符串(number:'*')  
                // this.number=0;//有效  
            }  
        }  
    }  
</script>  

操作步骤:

  • input绑定值为空字符,动态设置内容为数值0无效

预期结果:

  • 数值0应该显示

实际结果:

  • 数值0不显示

bug描述:

微信平台:

  • 当input绑定值为空字符串的时候,设置number为0无效
  • 当input绑定值为非空字符串的时候,设置number为0有效

安卓和IOS经测试无上述问题


更多关于uni-app input绑定值为空字符时,动态设置内容为数值0无效的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于uni-app input绑定值为空字符时,动态设置内容为数值0无效的实战教程也可以访问 https://www.itying.com/category-93-b0.html


uni-app 中,如果你尝试通过 v-model 绑定一个输入框的值,并且当输入框的值为空字符串时,你希望动态将其设置为数值 0,可能会遇到一些问题。这是因为 v-model 默认会将输入框的值绑定为字符串类型,而当你尝试将其设置为数值 0 时,可能会导致绑定失效或不一致。

解决方法

你可以通过以下几种方式来解决这个问题:

1. 使用 watch 监听输入值的变化

你可以在 watch 中监听输入值的变化,当检测到输入值为空字符串时,手动将其设置为 0

<template>
  <input v-model="inputValue" type="text" />
</template>

<script>
export default {
  data() {
    return {
      inputValue: ''
    };
  },
  watch: {
    inputValue(newVal) {
      if (newVal === '') {
        this.inputValue = 0;
      }
    }
  }
};
</script>

2. 使用 computed 属性

你可以使用 computed 属性来处理输入值,当输入值为空字符串时,返回 0

<template>
  <input v-model="computedValue" type="text" />
</template>

<script>
export default {
  data() {
    return {
      inputValue: ''
    };
  },
  computed: {
    computedValue: {
      get() {
        return this.inputValue;
      },
      set(newVal) {
        this.inputValue = newVal === '' ? 0 : newVal;
      }
    }
  }
};
</script>

3. 使用 input 事件手动处理

你可以在 input 事件中手动处理输入值的变化,当输入值为空字符串时,将其设置为 0

<template>
  <input :value="inputValue" [@input](/user/input)="handleInput" type="text" />
</template>

<script>
export default {
  data() {
    return {
      inputValue: ''
    };
  },
  methods: {
    handleInput(event) {
      let value = event.target.value;
      if (value === '') {
        value = 0;
      }
      this.inputValue = value;
    }
  }
};
</script>
回到顶部