Methods in Vue with the Composition API — Transcript

Transcript of the free Vue.js lesson Methods in Vue with the Composition APIwatch the video lesson.

push. push into a named method. So let's do that. Inside of the script section, I'll create a function called save item.

Next, I'll copy our code from the submit event. and add it to the method. One thing to note here is that when you're inside of the script section, in order to access the value of some kind of reactive reference, such as items or header, you actually have to use a special property named dot value. The reason for this is because Vue uses proxies in order to create reactive data.

This works great for data structures such as arrays, and objects. However, that's not the case for primitive types, such as strings, numbers, and booleans. Therefore, whenever you call the ref function, what's returned is a reactive object with your actual data stored on the value property. We'll learn more about the ref function, as well as its close sibling, reactive, in a later lesson.

All right. Let's make sure we don't forget to include this dot value on our other refs here as well. Nice. Now we can call our method on the submit event.

And notice that we didn't even have to provide the parentheses at the end of the function. It's completely optional when you're calling methods on events like this in view. All right. If we give things a try, Everything still works.

Great. We've taken some great strides to make our template easier to read and maintain. By removing the logic from our template to its own method, we can write cleaner JavaScript and provide clear method names so that we can better understand what our templates are doing. Plus, this will make future maintenance, testing, and debugging much easier for us to understand.

Even with those awesome improvements though we're not quite done yet. Notice that when we add a new item that the old item sticks around in our input. That's because we're not resetting our new item when we add it to our items. All right.

To fix that we'll set new item to an empty string at the end of our save item method. Don't forget. We need to use dot value here because we're referencing a reactive ref. Let's give it a try.

And great, it worked. Resetting data in the client might be a little different than what you're used to, especially if you're coming from a language like PHP. With Vue, we have to be mindful that we're in charge of maintaining the state of our app for our users. This is an important part of the user's experience, so we need to make sure that we're not leaving any data behind.

With our template cleaned up and refactored to avoid future issues, we've finished adding the functionality to save our new items. Awesome. In the next lesson, we'll work on hiding our form when we're not using it.