DEV Community

loading...
Cover image for Vue Academy #2: V-model directive

Vue Academy #2: V-model directive

CodeOz
Creator of https://www.chillflix.art 💻 4+ years of coding ! https://twitter.com/Code__oz📝 Love writting article dev and sharing ressources !
・Updated on ・2 min read

Welcome to the second vue academy ! It will be a list of lot of article on vue! I have 2.5 years of experience in this and I can teach a few thing about this !

For this course we will focus on v-model directive !

Let's start

First problematic, how do we manage an input value in <input> ?

We could do the next :

<script>
export default {
  name: "HelloWorld",
  data: function () {
    return {
      message: '',
    }
  },
  methods: {
     updateMessage(event) {
         this.message = event.target.value
     }
  },
};
</script>

<template>
<div>
    <input
        :value="message"
        @input="updateMessage"
        >
</div>
</template>
Enter fullscreen mode Exit fullscreen mode

We need to bind value of input to our current data message and handle event from this input in order to update our current data message.

It's not really friendly and we have to do this for every component...

v-model

You can use the v-model directive to create two-way data bindings on form input, textarea, and select elements. It automatically picks the correct way to update the element based on the input type.

So we can replace the code above by

<script>
export default {
  name: "HelloWorld",
  data: function () {
    return {
      message: '',
    }
  },
};
</script>

<template>
<div>
    <input v-model="message">
</div>
</template>
Enter fullscreen mode Exit fullscreen mode

We can remove the method that update value ! Since v-model will directly update it.

It's very useful !


I hope you like this reading!

🎁 You can get my new book Underrated skills in javascript, make the difference for FREE if you follow me on Twitter and MP me 😁

Or get it HERE

🎁 MY NEWSLETTER

☕️ You can SUPPORT MY WORKS 🙏

🏃‍♂️ You can follow me on 👇

🕊 Twitter : https://twitter.com/code__oz

👨‍💻 Github: https://github.com/Code-Oz

And you can mark 🔖 this article!

Discussion (11)

Collapse
nicks101 profile image
Nikki Goel

Nice short intro.
Looking forward to next one.

Collapse
codeoz profile image
CodeOz Author

thank you Nikki !

Collapse
siyafash98 profile image
Siyabonga Msibi

This is great. Thank you. Looking forward to the next one.

Collapse
codeoz profile image
CodeOz Author

Thanks Siyabonga

Collapse
rogerioviana profile image
Rogerio Viana

Nice post!

Collapse
codeoz profile image
CodeOz Author

thanks Rogerio !

Collapse
fiddlesmic profile image
FiddleSmic

Nice !

Collapse
fiddlesmic profile image
FiddleSmic

Nice !

Collapse
codeoz profile image
CodeOz Author

Thanks Fiddle!

Collapse
xlifems profile image
xlifems

Good!

Collapse
codeoz profile image
CodeOz Author

Thanks xlifems! Like your picture!