Define and Use Methods in the Vue Configuration Object for Complex Logic

Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 2 years ago

We'll explore the methods key of the Vue configuration object and how we can reference these methods in our code. Using these we can encapsulate more complex logic and use these throughout our application.

You will see how to pass values to these methods as well as see what happens when you don't pass arguments to a method that is expecting some.

Instructor: [0:00] If we would like to capture more complex logic for our onClick events or any other event we want to bind in Vue, rather than parsing a single expression in, we'll need to use a method. Methods are defined in our configuration object.

[0:15] So far, we have used the data function, which returns a object of props that are available within our Vue app. The next element of the configuration object we're going to use is the methods key. This methods key takes a value of an object. Within this object, we have functions that are accessible and usable by our Vue application.

[0:39] In our case, let's introduce a function called updateCart. This function is going to add one to the cart, but also take one away from the tickets, because we don't want to sell more tickets than we have. When we want to use props within the context of our method, we have to use the "this" keyword. We do this.cart++, and this.tickets--. Back in our index.html, we replace the our cart++ with our updateCart function like that. Then we can add our tickets on.

[1:15] We have a problem because we're selling more tickets than we have. We've got this down to -2 and our cart to 12. Let's stop that from happening. For our button, let's add a v-if directive, and let's only render this if tickets is greater than zero. Now, if we add to get to 10, our button is gone and we're sold out. Awesome.

[1:39] What if we wanted to add a second button that instead added two tickets rather than one? At the moment, our Add Two Tickets button is just adding one. We can parse through a variable, so instead of, update cart, on its own, we could parse through the number and use that in our method.

[1:58] Let's update our method to be able to accept that value. Accept the number, and add that number onto our cart. Let's take that number away from our tickets. Now, 2, 4, 6, 8, 10. What about our Add Ticket button? When we try to purchase with that, we are having this strange thing happen up here.

[2:23] What's happening is that by default, when we don't have parenthesis after our function, we parse through the click event. This is zero plus the click event that's being rendered here. There are two ways to solve this. The first is we could parse through a one, in which case it works like we expect it to. The second is we don't parse through any variable, and instead declare a default value in our method itself.