Header Ads

Learn Vue.js Step By Step: Event Listeners


In our previous lesson we've learned about List Rendering. In this lesson we will be talking about event listeners in Vue. Attaching event listeners in Vue is as easy as adding a directive in your HTML element using either the v-on or the shorthand equivalent @ which I prefer.

Using our previous example, let's say we want to add a movie title dynamically using input box and button. How are going to do that?
<!DOCTYPE html>
<html>
<head>
<title>My Favorite Movies</title>
</head>
<body>
    <div id="app">
        <h2>My Favorite Movies</h2>
        <ul>
            <li v-for="movie in movies" v-text="movie.title"></li>
        </ul>
        <input v-model="title">
        <button @click="add">Add</button>       
    </div>

    <script src="https://unpkg.com/vue"></script>
    <script>
        new Vue({
            el: '#app',
            data: {
                title: '',
                movies: [
                    {title: 'The Shawshank Redemption'},
                    {title: 'Hachiko'},
                    {title: 'About Time'}
                ]
            },
            methods: {
                add() {
                    this.movies.push({title: this.title});
                    this.title = '';
                }
            }
        })
    </script>
</body>
</html>
As you can see, when we run this code in the browser it is exactly what we want. Let me explain it one by one.

First, is we add a v-model="title" directive to the input box and initialize it in the data object property. Next, we add a click event listener to the button element using the @click="add", which means that, when the button is clicked the add() method in methods object will be triggered. Then in the add method we access the movies and title properties using the this keyword. Because everything in the data object property is reactive, every time we execute the this.movies.push({title: this.title}); everything will be automatically updated. Lastly, we empty out the input box by assigning the title with empty string (this.title = '';).

That's all for this lesson. For the detailed information about this topic please refer to the official documentation here. If you have some questions please write it down in the comment below, and see you in the next lesson.

Previous: List RenderingNext: Dynamic Styles and Classes


No comments