The v-model Magic

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..

<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.

<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.

    <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.

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

    <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.

    <HelloWorld v-model="helloClicked" />


    This is equivalent to -

    <HelloWorld v-bind:value="helloClicked" v-on:input="helloClicked = $event" />

Know More

 

comments powered by Disqus