首页 > 解决方案 > VUE.JS + Bootstrap - How to capitalize first letter in the same input

问题描述

I would like get in input capitalize first letter when I'm starting write.

<b-form-input v-model="formSurname" id="Surname" name="Surname" placeholder="Surname" type="text" maxlength="50" required> </b-form-input>

I have also filter for this. But v-model="formSurname | capitalize" doesn't work I tried :value="formSurname | capitalize" but it doesn't work too

Vue.filter("capitalize", function (value) {
    if (!value) 
        return '';
    value = value.toString();
    return value.charAt(0).toUpperCase() + value.slice(1);
});

How to make an input to change my first letter in real time?

标签: vue.jsvuejs2bootstrap-vue

解决方案


If you need to store the value with the uppercase, use a computed property with set and get methods :

computed: {
 formSurnameCapital: {
    get: function () {
      return this.formSurname;
    },
    // setter
    set: function (newSurname) {
      if(newSurname.length < 1) {this.formSurname = ''; return}
      this.formSurname = newSurname.replace(/^./, newSurname[0].toUpperCase());
    }
  }
}

And in your template :

<b-form-input v-model="formSurnameCapital" id="Surname" name="Surname" placeholder="Surname" type="text" maxlength="50" required> </b-form-input>

Else, if is just about displaying it uppercase, you can simply use css :

.toCapitalFirst {
  text-transform: capitalize;
}

推荐阅读