This page looks best with JavaScript enabled

The v-model Magic

 ·   ·  ☕ 2 min read

In a previous post, we saw the power of bindings in Vue.

v-model is a powerful way to bind variables and UI rendering in Vue. Let us look at a bit more of v-model in this post.

Remind me what is v-model about?

In its simplest form..

1
<input type="text" v-model="myName" label="Your name:">

.. and it doesn’t quite get more complicated than that on its own.

When you change ‘myName’ manually, through another component, or from the back-end, the variable value changes for sure but will also trigger off a change to UI. The user will see near instantaneous change to a specific UI element without any page refresh.

v-model enforces a two-way bind. As you change the input text box, the value ‘myName’ changes and this can further drive changes to another UI element. In our case, the below p tag continuously keeps changing as you type in the input box.

1
<p v-if="myName">You entered: {{ myName }}</p>

Modifiers

You could add more power to v-model using the following directives -

  • lazy refresh


    Wait for model to ‘change’ rather than just ‘input’. When you type in the input box continuously, each key may be considered an input - a change may be triggered milliseconds (or event loops) later when the variable does get changed. When the immediate change is not essential, it is a good practice to wait for the change to happen before triggering UI refresh.

    1
    
    <input type="text" v-model.lazy="myName" label="Your name:">
    
  • apply changes to the value or the type of value


    v-model provides you with additional modifiers that can help treat the input value as a number, or truncate strings etc.

    1
    
    <input type="text" v-model.trim="myName" label="Your name:">
    
  • hierarchical variables are not a problem

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    
    <template>
    // code  ...
    
    <input type="text" v-model.trim="myName.first" label="Your first name:">
    
    // ... more code
    </template>
    
    <script>
      export default {
        name: "HelloWorld",
        data() {
          return {
            myName: {
              first: "John",
              last: "Doe",
            }
            showHello: false
          };
        },
      };
    </script>
    
  • apply changes on components too!


    An event on UI is boiled up and bound to an action instead of just the value output by an event.

    1
    
    <HelloWorld v-model="helloClicked" />
    

    This is equivalent to -
1
<HelloWorld v-bind:value="helloClicked" v-on:input="helloClicked = $event" />

Know More

 

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things