Event Handling

vue.js logo

A little HTML, CSS, & JavaScript knowledge if recommended for this course.

To follow along, the starter folder is located in The Vue instance lesson.

The v-on directive

In addition to the directives we have looked at so far, which include v-for and v-bind, we will now discover another useful directive called v-on. The v-on directive will allow us to react to events such as a mouse click.

This v-on directive is also used in HTML elements as an attribute, and we are going to use it to change between light and dark mode when a user clicks on a button, meaning we need a button in the HTML:

<main>
  <div class="blog_wrapper">
    <!-- add button element -->
    <button v-on:click="">toggle</button>

v-on shorthand syntax

There is also the @ shorthand for this to make it shorter:

<main>
  <div class="blog_wrapper">
    <button @click="">toggle</button>

Here we are listening for a click event but other JavaScript events can be used too such as onsubmit and onmouseover. To use them we remove the on prefix, so onclick becomes click and so on.

Toggling dark mode using v-on

Next, we need to do something when the button is clicked. Let’s toggle the setDarkMode data property:

<button @click="darkModeSet = !darkModeSet">toggle</button>

Try this out by clicking the toggle button. This should switch between the light/dark modes!

This toggle button is not the best looking. We can improve this by adding a HTML entity to show a moon icon on light mode, and a sun icon on dark mode.

To toggle between these icons, add a JavaScript expression which we learned about in the previous lesson:

<button @click="darkModeSet = !darkModeSet">
  {{ darkModeSet ? '&#9788;' : '&#9789;' }}
</button>

Try this out by clicking the button. You can also test this with other events such as mouseover.

Using JavaScript expressions in our click event like this is fine for simple examples. For more complex cases we may want to extract this into a function or a method, and we will do this next.