【问题标题】:MaxLength for bootstrap-vue input number Vue.jsBootstrap-vue 输入数 Vue.js 的 MaxLength
【发布时间】:2020-06-04 19:45:57
【问题描述】:

我尝试为来自bootstrap-vue 的输入实现maxLength,但从我从他们的文档中读到的内容来看,它们不支持最大。如果我删除type="number",它可以工作,但不再是数字了。

    <b-form-input
        size="sm"
        v-model="register_volume_first"
        type="number"
        maxlength=4
        placeholder="1902"
    ></b-form-input>

【问题讨论】:

  • maxlength 仅适用于文本输入。使用 minmax 进行数字类型输入:min="1000" max="9999" step="1" 确保有 4 位数字且没有小数。但请注意,这只适用于验证输入的情况。

标签: javascript vue.js vuejs2 vue-component bootstrap-vue


【解决方案1】:

尝试使用formatter prop如下:

<template>
  <div>
    <b-form-input size="sm" v-model="volume" type="number" :formatter="formatYear" placeholder="1902"></b-form-input>
       <div class="mt-2">Value: {{ volume }}</div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
       volume: '4'
      }
    },
methods:{
  formatYear(e){
     return String(e).substring(0,4);
  }
}
  }
</script>

【讨论】:

  • 谢谢,但在我的情况下,用户不会使用箭头插入数字(年份)
  • 正是我需要的!谢谢!
【解决方案2】:

maxLength 仅适用于文本类型,我尝试进行测试以查看是否支持 min 和 max,似乎支持,请看一下:

new Vue({
  el: '#app',
  methods: {
    onSubmit(evt) {
      evt.preventDefault()
      console.log(evt)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>

<div id="app">

  <b-form @submit="onSubmit">
    <b-form-input type="number" max="20" min="10"><min="10" required></b-form-input>
    <b-button type="submit" variant="primary">Submit</b-button>
  </b-form>

</div>

请记住,在提交表单时会检查最小值和最大值,当然需要使用所需的参数。

编辑:添加表单并提交到 sn-p

编辑 2: 无表单提交

new Vue({
  el: '#app',
  methods: {
    onSubmit(evt) {
      evt.preventDefault()
      console.log(evt)
    }
  },
  data() {
    return{
      inputValue: 15
    }
  },
  watch: {
    inputValue(val){
      if(val < 10)
        this.inputValue = 10;
      else if(val > 20)
        this.inputValue = 20;
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>

<div id="app">


    <b-form-input v-model="inputValue" type="number" max="20" min="10" required></b-form-input>


</div>

【讨论】:

  • 好的,谢谢,但我正在寻找一种不依赖于提交的方法。
  • @Beusebiu 在输入中添加一个 v-model 并观察它。
  • 我感谢了一块手表,但我不确定里面写了什么。
  • @Beusebiu 我编辑了我的答案,看看 Edit 2 是否让你满意。
  • 我检查了它,但不工作。仅当我使用箭头时才有效。
猜你喜欢
  • 2021-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-17
  • 2016-05-20
  • 2021-08-17
  • 2021-06-23
  • 2019-01-29
相关资源
最近更新 更多