Bind Values to Input Fields in Vue.js

Greg Thoman
InstructorGreg Thoman

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 4 years ago

Use v-model to create 2-way data binding. You can render dynamic options in a select element and bind them to their data. Use v-bind on inputs to use dynamic properties on the Vue instance. Adding modifiers like .lazy, .number and .trim allow us to trim our methods and let Vue take care of things like trimming white space.

[00:00] We're starting with an empty view component. Let's add an attribute called checked. In our component, let's add a check box and add v model checked. For the label, let's just create a ternary. If checked, display the string checked, else, unchecked.

[00:17] For radio boxes, let's add a dino array and an attribute for chosen dino to our data block. In the component, let's create a template and list out dinos. Each one will have an input of type radio. Let's bind the value to dino and set v model equal to chosen dino. Then let's add a span to show our chosen dino.

[00:43] For multi-select, let's add a select periods attribute and a periods array. We'll open a select element and set v model equal to selected periods. Then, let's iterate through the periods setting v bind value to period.value and we'll display the name. Let's create another span to show the selected periods.

[01:10] Now let's set the attribute single to an empty string and create a simple input field and set v model to the attribute single. After, let's render single in a paragraph tag.

[01:24] What about a multi-line input? Let's add an attribute for message, then a text area with v model set to message. We'll add a placeholder for fun. To render the message as multi-line, let's create a paragraph with its style attributes set to white space pre and render the message inside of it.