Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Marina Mosti
Marina Mosti

Posted on • Edited on

     

Hands-on Vue.js for Beginners (Part 2)

Last time (in part 1 of this series) we figured out how to addVue to our index.html with a regular<script> tag, and we managed to add our very first reactive property to the page. Today, let's learn how we can change this property with user input.

Our code so far looks like this:

<html><head><title>Vue 101</title></head><body><h1>Hello!</h1><divid="app"><p>My local property: {{ myLocalProperty }}</p></div><scriptsrc="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script><script>constapp=newVue({el:'#app',data:{myLocalProperty:'Im a local property value'}});</script></body></html>
Enter fullscreen modeExit fullscreen mode

Listening to user events

In order to better showcase the reactivity ofVue, and to learn how to react to user events we are going to add a button to our app that will change the value of ourmyLocalProperty prop.

Go ahead and first add a new button to our<div>.

<divid="app"><p>My local property: {{ myLocalProperty }}</p><hr><button>Click me</button></div>
Enter fullscreen modeExit fullscreen mode

Now, how do we react to this button getting clicked?

If you come from ajQuery background your instinct may be to try to do something like this:$('button').click();, however, there's a golden rule inVue. NEVER manipulate the DOM (elements in the page's HTML) directly.

Without going into super intricate details,Vue keeps a virtual "copy" of your HTML (in this case our div with the "app" ID) and automagically 🧙‍♀️ 🧙‍♂️ figures out where and how to update it when properties change.

If you make changes to the DOM directly with JavaScript, you risk losing these changes and unexpected behavior whenever Vue re-renders the content, because it will not be aware of these changes.

Enough theory though, let's move on with the clicking. Add thisevent handler to our button:

<buttonv-on:click="myLocalProperty = 'The button has been clicked'">Clickme</button>
Enter fullscreen modeExit fullscreen mode

A couple of things are happening here.

v-on:click="" InVue we have these"directives" that we can add to our HTML content.

A directive simply put is an HTML parameter thatVue can understand.

In this particular case, we are tellingVue:Vue (v-),on the user'sclick do this:"myLocalProperty = 'The button has been clicked'", which is simply an inline declaration to change the value of our property.

If you go ahead and open yourindex.html file now in the browser and click the button, you will see the string that we interpolated earlier inside the{{ }} in our code will react to our button modifying the property.

Alternate syntax

In most places you will most likely not find events being set on the HTML withv-on:[eventname] as we have in this example because inVue we have a very handy shorthand for this type of thing.@[eventname].

Let's change our<button> click even to to use this shorthand:

<button@click="myLocalProperty = 'The button has been clicked'">Clickme</button>
Enter fullscreen modeExit fullscreen mode

Methods

In most cases, when a user event like theclick of a button is fired, you will need to do a lot more than changing the value of a variable. So let's learn aboutmethods (aka, functions).

To continue with our example, let's make the button call a function that will do something really simple, it'll change the value ofmyLocalProperty by appending a random number to a string.

Delete our previous implementation of@click and replace it with this:

<button@click="buttonClicked">Clickme</button>
Enter fullscreen modeExit fullscreen mode

Notice that we're not adding a() after"buttonClicked". We can omit these when we are not passing any arguments to our function. For example,@click="changeName('Marina')". (More on this later when we look at conditional rendering 🙂)

Now that we have our button ready to executebuttonClicked on clicks, we need to actually write this function.

Vue has a special place to write functions that ourVue instance can use. This place is inside the{ } we passed to ournew Vue({}) line before.

We will create amethods: {} property that will hold an object filled with our functions.

<script>constapp=newVue({el:'#app',data:{myLocalProperty:'Im a local property value'},methods:{// 1buttonClicked(){// 2constnewText='The new value is:'+Math.floor(Math.random()*100);// 3this.myLocalProperty=newText;// 4}}});</script>
Enter fullscreen modeExit fullscreen mode

Let's dissect this:

  1. We declare themethods property inside ourVue instance. As I mentioned, in here you will put all your instance methods/functions.
  2. Inside themethods object{ } we declarebuttonClicked(), which is the function we are trying to call on our@click listener. We're not going to use any parameters at this point so empty().
  3. We join the value of the rounded down valueMath.floor of the result of multiplying the random value of 0-1 by 100 to a string and store it in a constant.
  4. We assign the value of our new string tomyLocalProperty. Now be very careful aboutthis tiny detail 🙃 (lame pun intended). When we assign new values to the properties inside the instance'sdata property (the one insidedata: {}) youMUST access it throughthis.[prop-name].

In the context of a method the keywordthis refers to theVue instance. Vue will perform some magic behind the scenes so that you can read/write to your properties insidedata by doingthis.property = value.

Now that we have everything set up, reload yourindex.html file and click on your button. The value of our interpolated{{ }} string on the containing<p> will be updated every time you click the button, for every single time thebuttonClicked function is executed. Once again, the magic of Vue's reactivity is coming into play.

Wrapping up

If at this point you're thinking,well, this is really easy then you're on the right track. One of the things I love the most about this framework is its clear syntax and simplicity. Itjust works. But this should not be confused with thinking that Vue is not powerful.

We're merely scratching the surface of what we can do with Vue so far, but you'll see as we progress through these articles that these tiny building blocks put together will soon make the core of your amazing next app.


Stay tuned for part 3!

Top comments(25)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
frfancha profile image
Fred
  • Joined

Really like it, I hope you will go through the full Vue features because if all is explained with the same quality that will be by far the best tutorial to Vue.

CollapseExpand
 
marinamosti profile image
Marina Mosti
Marina Mosti is a full-stack web developer with over 14 years of experience in the field. She enjoys mentoring other women on JavaScript and her favorite framework, Vue.
  • Joined

Hi Fred, thanks for your kind words. That's the plan, to do a weekly release and walk through every feature!

CollapseExpand
 
superterrific profile image
Dana Byerly
Interaction designer who codes. Eleventy super fan.
  • Location
    New York City
  • Joined

Thank you, this helped me better understand a Vue app I cobbled together from examples! Really appreciate the clear explanation and dissection.

And, more excitingly, within minutes of reading this I was able to refactor the previously mentioned app to use a click event to call the method with an API call, replacing the window.location.reload(true) full page reload. Thanks again ⚡️👍🏼

CollapseExpand
 
marinamosti profile image
Marina Mosti
Marina Mosti is a full-stack web developer with over 14 years of experience in the field. She enjoys mentoring other women on JavaScript and her favorite framework, Vue.
  • Joined

Awesome Dana!!! Next week ill go into conditional rendering so stay tuned :)

CollapseExpand
 
imbhargavreddy profile image
Bhargav
First of my kind. Learn.apply.repeatConsistency is the key.
  • Location
    Jalandhar
  • Education
    Lovely Professional University
  • Work
    Student at LPU
  • Joined

Thank you very much for taking the effort to teach. These tutorials are amazing compared to video lectures. Learning from text tutorials is helping a lot. I hope you will take us to the core of Vue with the same(or >=) passion.

CollapseExpand
 
mikefromru profile image
Mike
My morning begins with coffee and Twitter.
  • Joined

Thank you so much for this acticle. Would be nice if you create tutorial that show how to use Django Rest Framework with Vue.js. I mean registration with confirmation an email, login, change a pass, login with Facebook, Google etc...

CollapseExpand
 
straleb profile image
Strahinja Babić
Am a freelance self-taught Web-Designer.👨‍🎨Love creating new stuff and love learning about new things 🙂I speak 3 languages: English, German and Serbian(native)🤓Twitter account @Strale_B
  • Location
    Bosnia and Herzegovina
  • Education
    Mechanic engineering
  • Joined
• Edited on• Edited

Wow awesome article, makes me wanna do something with Vue again 😊

CollapseExpand
 
marinamosti profile image
Marina Mosti
Marina Mosti is a full-stack web developer with over 14 years of experience in the field. She enjoys mentoring other women on JavaScript and her favorite framework, Vue.
  • Joined

Do eeeeet! :D

CollapseExpand
 
akwetey profile image
Jonathan Akwetey
I'm a passionate developer
  • Location
    Accra
  • Work
    Fullstack developer at Fundihub
  • Joined

another great work.. waiting for more..👏👏👏

CollapseExpand
 
marinamosti profile image
Marina Mosti
Marina Mosti is a full-stack web developer with over 14 years of experience in the field. She enjoys mentoring other women on JavaScript and her favorite framework, Vue.
  • Joined

Thanks Jonathan! Comments like these keep me motivated :)

CollapseExpand
 
4m3r profile image
Amer
  • Joined

Great also waiting for more. Thx

CollapseExpand
 
marinamosti profile image
Marina Mosti
Marina Mosti is a full-stack web developer with over 14 years of experience in the field. She enjoys mentoring other women on JavaScript and her favorite framework, Vue.
  • Joined

Thanks!

CollapseExpand
 
abidemit profile image
Tiamiyu Sikiru Abidemi
Javascript Frontend Developer and GDG Ibadan Organizer
  • Email
  • Location
    Ibadan, Oyo State, Nigeria
  • Education
    Lead City University
  • Work
    Frontend Developer
  • Joined

Explanation on point, helped me understanding the basics better.

CollapseExpand
 
marinamosti profile image
Marina Mosti
Marina Mosti is a full-stack web developer with over 14 years of experience in the field. She enjoys mentoring other women on JavaScript and her favorite framework, Vue.
  • Joined

Thanks for your feedback :)

CollapseExpand
 
suryanarayana profile image
SURYA NARAYANA MURTHY
Being a Web Developer I do continuously learning new technologies and applying it in projects.
  • Location
    Bengaluru
  • Work
    Lead Engineer in Development. at Nalashaa Solutions
  • Joined

I like the articles on Vue that you have posted. Great tutorials parts. I am learning Vue and doing POC'S on it.

If possible can you post any articles on Vuex and Vue-Router with Vue.

CollapseExpand
 
marinamosti profile image
Marina Mosti
Marina Mosti is a full-stack web developer with over 14 years of experience in the field. She enjoys mentoring other women on JavaScript and her favorite framework, Vue.
  • Joined

Hey Surya, thanks for you words :) Keep posted on my twitter account@marinamosti, I post new articles there and will have a Vuex series up soon I hope!

CollapseExpand
 
suryanarayana profile image
SURYA NARAYANA MURTHY
Being a Web Developer I do continuously learning new technologies and applying it in projects.
  • Location
    Bengaluru
  • Work
    Lead Engineer in Development. at Nalashaa Solutions
  • Joined

Thank you :)

CollapseExpand
 
rodz profile image
Rodrigo Gomez
  • Joined

Nice follow up on the first tutorial. I like the explanations of what Vue is doing behind the scenes.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Marina Mosti is a full-stack web developer with over 14 years of experience in the field. She enjoys mentoring other women on JavaScript and her favorite framework, Vue.
  • Joined

More fromMarina Mosti

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp