Everyday, I publish here on Dev.to what I learn from my Vue course the day before.
Click follow if you want to miss nothing.
Without further ado here is a summary of my notes for day 2.
My First button click
Vue.js is reactive, that mean I can react to user event like a button click
let's create an example. Open index.html (see yesterday lessons for reference) and add a button:
<div id="app">
<h1>{{ message }}</h1>
<p>{{ number1 + number2 }}<p>
<button>Change message</button>
</div>
Like you can see we add a button html tag. The button text is 'Change message'. For now the button do nothing.
Let's add an event click to this button:
<button v-on:click="">Change message</button>
The v-on:click is a Vue.js directive. That directive tell Vue that on click event execute the code between the double quote.
Let's add some action into those double quote:
<button v-on:click="message = 'New Message'">Change message</button>
So that's pretty logic. We set message equal to a new value.
When we will click the button Vue will re-render that part of the DOM and the new message will be display right away.
Try clicking that button right now in the browser:
Note that the event could be anything else. For example we could change the message only on double click:
<button v-on:dblclick="message = 'New Message'">Change message</button>
Or for example we could change the message when mouse first move over the button.
<button v-on:mouseenter="message = 'New Message'">Change message</button>
As we progress throughout the lesson we will learn and use many more events.
Event could also be attach to almost any html tag, not just button. For example we could have an v-on:click event link to a div:
<div v-on:click="message = 'New Message on div click'">
This is div content
</div>
Event can be execute inline or reference to a method:
<button v-on:click="changeMessage()">Change message</button>
The reference method need to be present inside our Vue code:
const app = Vue.createApp({
data() {
return {
message: 'Hello World Vue',
}
},
methods: {
changeMessage() {
this.message = 'New message from method'
}
}
})
app.mount('#app')
We add a methods property. That property will contain all methods definition we want to use inside our Vue.js component
Note we can also pass a parameter to the method:
methods: {
changeMessage(message) {
this.message = message
}
}
An change our html accordingly:
<button v-on:click="changeMessage('My custom message')">Change message</button>
Last but not least the v-on directive can bee replace with a shortcut directive of @:
<button @click="message = 'New Message'">Change message</button>
Conclusion
That's it for today. Tomorrow the journey continue, see you later! If you want to be sure to miss nothing click follow me here or on twitter!
Follow me on Twitter: Follow @justericchapman
Top comments (1)
A good read.