Directive to change md-input in vue-material

666 Views Asked by At

I needed to change the value in a vue-material md-input box as the user typed (for ease of understanding the problem, say I needed to capitalize all the letters).

Simple answers like using v-bind or calculated values don't play well with vue-material:

<md-input v-bind="val" />

partially because it doesn't support v-bind in the vue-material components, and partially because while a calculated value does work, setting the value triggers a new get and the cursor location goes to the end of the string.

So the question (which I will answer, but I'd appreciate it if others have a better answer) is how do I modify the value in a vue-material component such as md-input?

1

There are 1 best solutions below

0
On

In order to make md-input work when modifying input values, I created a custom directive like this:

directives:
    {
        allCaps:
        {
            bind: function (el, binding, vnode)
            {
                var allCapsInput = function (e)
                {
                    var s = e.target.value;
                    var uc = s.toUpperCase();
                    if (uc != s)
                    {
                        var start = e.target.selectionStart;
                        var end = e.target.selectionEnd;
                        e.target.value = uc;
                        e.target.setSelectionRange(start, end);
                        vnode.elm.dispatchEvent(new CustomEvent('input'));
                    }
                };
                el.addEventListener('input', allCapsInput);
            }
        }
    }

This combines the suggestion of making a directive from marcosmoura from the vue-material issue list where he suggests:

To create a directive, like v-mask, and manipulate the value of the element. This is the best way since you can reuse this through your application and even make this as an open source library.

With the base code and answer from this question

Along with the cursor control from lifo101's answer to this forum post

The input and model are updated in real-time and as a bonus the text caret position is not lost.

Which I modified slightly to include selectionEnd along with his selectionStart.