Posts Tagged “Frameworks”

Do you want to Create Custom Inputs With Vue.js ?

Do you want to Create Custom Inputs With Vue.js ?

Component-based libraries or frameworks such as Vue have given us the wonderful ability to create reusable components to be spread throughout their respective application, ensuring that they are consistent, and (hopefully) simplifying how they are used.

In particular, form inputs tend to have plenty of complexity that you’d want to hide in a component, such as custom designs1, labels, validation, help messages, and making sure each of these pieces are in the correct order so that they render correctly.

On top of that though, Vue has a built-in directive called v-model that simulates 2-way binding by binding a value and capturing input events. If you’re going to build a custom input component, then you’ll definitely want to support the v-model directive.

Sadly, when I looked around for examples of custom inputs in Vue for radio buttons or checkboxes, they either didn’t take v-model into consideration at all, or they failed to implement it correctly. There is some decent documentation for custom text inputs2, but since it doesn’t explain customizing radios or checkboxes, we’ll discuss that here.

This tutorial aims to help you…

  1. Understand how v-model works on native inputs, focusing primarily on radios and checkboxes
  2. Understand how v-model works on custom components by default
  3. Learn how to create custom checkboxes and radios that emulate how v-model works on them natively

Quick note before we get started: ES2015+ code will be used throughout the code examples. I’ll also be favoring the Single File Component3 syntax over using Vue.component or new Vue.

Further Reading on SmashingMag: Link

How Does v-model Work Normally? Link

The official Vue documentation8 is actually pretty good on this topic, but there are a few minor blind spots. In any case, we’ll be trying to cover it pretty thoroughly here.

In essence, v-model is just a shorthand directive that gives us 2-way data binding, and the code it is shorthand for depends on what type of input it is being used on.

Text Boxes Link

<input v-model="message" placeholder="edit me"> <p>Message: {{ message }}</p> <!-- OR --> <p>message:</p> <p style="white-space: pre-line">{{ message }}</p> <textarea v-model="message" placeholder="add multiple lines"></textarea>

When using a text input (including types such as email, number, etc.) or textarea, v-model="varName" is equivalent to :value="varName" @input="e => varName =". This means that the value of the input is set to varName after each update to the input varName is updated to the value of the input. A normal select element will act like this too, though a multiple select will be different.

Radio Buttons Link

So, what about radio buttons?

<input type="radio" value="One" v-model="picked"> <input type="radio" value="Two" v-model="picked"> <span>Picked: {{ picked }}</span>

read more

Read more »