Create and Manipulate State within a Vue Component by Defining Methods and Properties

Share this video with your friends

Send Tweet
Published 3 years ago
Updated a year ago

We'll see how we can add methods and properties to components, allowing us to keep the logic that controls our components together with the templates.

Our component receives tickets for the visitor to buy, we'll create a method in our component and bind it to a button that allows them to buy those tickets. In doing so, you'll notice that we can't change the value of the tickets that we received, it's immutable. To get around this we'll create a local variable in our component to update the display as tickets are purchased.

Instructor: [0:00] So far, we are parsing props into our component, defining what those props will be and their types, and using them in the template. We also defined this ticketsToBuy, which we set to zero. We can also define methods in our component in much the same way as we can in the Vue application.

[0:21] Let's do that. Let's add tickets. We'll parse a variable for the number of tickets. We'll say this.tickets -= number. In our component, let's have a button which adds tickets. Let's make sure this only appears if the ticketsToBuy is greater than zero, and have our @click to equal addTickets. We can parse it our num, which is ticketsToBuy, or we could have used this.ticketsToBuy in here.

[1:00] Let's have a look to see what's happened here. I've got my components. Let's look at the bronze components first. We see tickets history, ticketsToBuy is zero. Let's set ticketsToBuy to be two, and let's buy those tickets. You'll see that tickets is not decreasing. That's because the props are parsed on are immutable. We can't change them.

[1:18] What we need to do instead is introduce a variable such as ticketsLeft and initialize that with the incoming prop. This is the variable then that we're able to transform. We can see tickets history, ticketsLeft history, ticketsToBuy is zero. If I try to buy two tickets, then I've got one ticket left. Once I have bought those two tickets, I'm going to want ticketsToBuy to equal to zero.

[1:45] Try it again. Two tickets, buy those two tickets, that gets set to zero. There's one ticket left. You can see even though I bought those tickets, they're available to buy again. I'm going to update my number in tickets to number in ticketsLeft.

[2:04] Let's try again. Let's buy two tickets. We can see I've got one ticket left and there's only one ticket I can buy. I'm updating the data within my component. I can't alter the props, but I do need to tell my parent component, the root component, that I have changed this data and I want this data to change. We'll see how to do that in the next lesson.