Building a mdAutocomplete for vue-material framework

As always I’ll try to write as little as possible so you can get to the point ASAP.

General idea

The general idea is to create a component that works like an Autocomplete. The final component should have Material Design look and feel and should also reuse vue-material components. After searching and testing some “native” components from the framework, I decided to use the following:

  • mdInput: the mdAutocomple needs an input;
  • mdMenu: this component is key to make the mdAutocomplete work. After some try/errors, I realized this component is created as the last child of the body tag and it has a fixed position. I can rest assured it will be always rendered on top of everything.

The mdAutocomplete should have some properties too, like: working with a list or a fetch function and having a debounce and minChar options too. I wanted something like this:

mdAutocomplete example

Forking

After having the general ideal planned out, I forked the vue-material github and created a way to pull data from the original repository and make Pull Requests. To make this important step happen, all I had to do was to follow these instructions by @CristinaSolana (thank you).

Hacking v-model

No component is good enough without making use of the v-model ain’t it? After checking out the code, it took me a while to understand how the heck vue-material was making it work.

The v-model used on any component is binded to its scope! Meaning that you can’t access it outside the component. Even if you could make the v-model a property, it wouldn’t work. In other words (see the v-model as a property):

Every component instance has its own isolated scope. This means you cannot (and should not) directly reference parent data in a child component’s template. Data can be passed down to child components using props ~ vuejs.org

The trick was to remember that a v-model IS a value property and an input event. In code:

Of course, mdInput has some special functions that will make sure the change on v-model is effective. The hack itself includes these functions and knowing that a v-model is made by two parts.

Composing a new component

With all that in hand I built the mdAutocomplete. It is currently waiting on the Pull Request queue in vue-material repo and I can’t wait to people have it and use it. The whole code can be seen here or down below:

Making a Pull Request

This is the easiest part. Once I was done, all I had to do was to go to my forked vue-material repository, clicked on the New Pull Request button and making sure the base and base-fork was pointing to vue-material’s repository.