Event Listening In VueJS

Following the previous post on list rendering in VueJS, here is another one. In this one, we will see how we can use event listeners.

We will use the code from the previous post where we rendered a list from an array.

What we are gonna do here is dynamically add items to the list using an event listener.

Here’s our code for list rendering.

So, it uses the v-for directive to iterate through items from names and outputs them in HTML.

What we want to do is, add an option to add items to this list dynamically. For that we will create an input field and a button.

Then we will add an event listener to the button which will add the item from the input field to our list.

Let’s check out how we can do that. Check the code below.

Now let’s break it down.

We created an input field and we binded ‘newName‘ to that field.

Then we created a button and added an event listener. Notice the @click, this basically means on click. So when the button is click we will trigger the addName() function.

What addName() function does is – it takes the value of the input field which we binded to newName and it then pushes that value to the names list. After that it sets the value of newName to blank so that the input field is blank after the name has been added to the list.

For a better understanding of how this works, I have put together a fiddle. Go ahead. Put your name in the field and click on the button.

 

Hope this helps.

If you didn’t understand any of the parts or if you have any suggestions for me, please let me know through the comments.

Click Here to Leave a Comment Below

Leave a Reply: