How do I go about creating an always capitalized input in vue.js? How do I go about creating an always capitalized input in vue.js? vue.js vue.js

How do I go about creating an always capitalized input in vue.js?


You could create a custom directive.

Vue.directive( 'touppercase', {    update (el) {        el.value = el.value.toUpperCase()    },})

And then use it where you need. For example:

<input type="text" v-model="modelfield" v-touppercase>


Since you don't have a lot of code to run, you should manually bind events to your textfield and then handle the uppercasing there.

Handling events from a text field can be done by adding an input event handler on them, and then updating the initial state again.

<input :value="text" @input="updateText($event.target.value)"/>export default {    data() {        return {            text: '',        }    },    methods: {        updateText(newValue) {            this.value = newValue.toUpperCase();        },    }}

You can also do it inline in a template, but this might make it harder to read depending on your code style preferences

<input :value="text" @input="text = $event.target.value.toUpperCase()"/>


This directive works fine with v-model (last character is in upper case too):

Vue.directive('uppercase', {  update(el) {    const sourceValue = el.value;    const newValue = sourceValue.toUpperCase();    if (sourceValue !== newValue) {      el.value = newValue;      el.dispatchEvent(new Event('input', { bubbles: true }));    }  },});

Usage:

<input type="text" v-model="myField" v-uppercase />