EASY Vue 3 Composition API 🙌 [FULL TUTORIAL]

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi guys welcome to this video on the vue 3 composition api view 3 has unlocked brand new apis for us we're going to take a look at refs reactivity view x and lots more in depth when it comes to the composition api if you like this video and i've got loads more free content for you go ahead and hit that subscribe button hit that ding dong bell give us a nice big thumbs up it'll be very much appreciated let's get on with the video so why would we want to use the new view 3 composition api i first want to address that view 3 is not replacing view 2. in other words you can still write components the way you would from view 2 in view 3. with some slight modifications here and there however you can overall write your components the same way the composition api is graceful it's not a replacement so you can gracefully upgrade your components if you wish or you can leave them alone the second thing is why would you want to do it well when you see a composer you see a composer that has lots of notes on his sheet all those notes add up to a tune on that sheet and that's composable well i want you to think the same way here now at the moment if i look at this component it's fairly large it's got quite a bit of logic in there and of course when i'm creating methods that deal with that same property and computed properties that are dealing with the same data i kind of want my data more composable more closer together more well-defined what if i could actually do that so for example in this case instead of segregating out my code into computed or watched let's just say i can move the data closer to the methods and the computed property now all of my logic is coupled together and i can do that for everything so instead of me changing something and potentially breaking it or i see all of the parts of the component to deal with that data now i can with composition api because i can move things closer together and that really helps with readability not only does composition api make this more readable especially with larger and more complex components which will always exist in the spa world it allows for more reactivity control so this is something we'll tuck into later but what you will be able to do is you'll be able to control the reactivity so the first thing we're going to do is import what we need for the composition api the first thing will be importing ref reactive and computed from view itself so now that i've imported this from the view library i can now use this in the composition api of my component the next thing i want to do is create a setup method within my component and now we're going to transfer our data computed and methods into the composition api so the first thing we'll do with the setup method is use the ref function now the ref function is used for basic properties primitive properties like strings numbers booleans such as true and false anything like that a standard property that you would normally see in your data we can transfer over so we are going to create a constant and trust me you can still edit the value of these properties but i set them as constants initially so constants will be first name middle name and last name they are all string types therefore i can set them equal to ref and then pass in the default value the next thing that i need to do is convert my address object now the address property here is not actually a primitive value it's an object it's a more complex value type this is where reactive comes in so i'm going to set a constant then i'm going to call reactive and in there we're going to have an object next up we have computed so again i'm just going to create some constants and by the way i'm creating constants because whether using ref or reactive they're actually returning objects here and i don't actually want that bit to change so i'm setting these to constants so we're going to have constant full name formatted address and then we're going to call the computed method on those constants and make that equal to the value and of course the value that we're passing into computed is the function that we want to run when we want to display these computed props so at the moment this won't actually work because this is not populated you see setup is called before the component is initialized so before you turn the ignition and set everything up setup is running before that hence the word set up so we have to work with our properties a little bit differently in this instance we cannot use the this dot what we must do is target that proxy object that's created and we'll talk more about that later and you target it with the const far or let name that you've given it and then you use dot value that will ensure that when you're using refs you can use dot value now with reactive it's a little bit different you don't need to bother with dot value with the reactive but what you do need to do is access those properties directly since i've set this as a constant what i want to do is make sure that it's constantly reactive and therefore i don't want to replace the object what i want to do is target each individual property and reset it that is something you need to bear in mind when it comes to computed or methods or any sort of execution context within setup and that's how you access refs is you use dot value and then for reactive you target each individual property the final thing is a method now method doesn't need any sort of special hook or any sort of reference or reactivity and method is not actually that reactive and then all we need to do is actually just move the method into the setup and then what we need to do is create a return statement now whatever you return in this object it will actually produce that in the component so you can privatize things at this point i'd like to say there is a nice caveat to this you can actually create certain private properties or very private computed or whatever it is and not actually have that exported out into the component space for whatever reason that may be so you can actually have a bit more encapsulation in your components so all i'm going to do is use the es6 syntax and then just use the name of the constant let or var and what that does is it will use that as the key name and then it will go fetch the value and assign it so you can actually create an alias here so instead of first name you could create the key my name and then have the value as first name that reactive property there so that is possible in this case if you'd like to do that so another nice little caveat but normally for the most part you don't need to now it's also very important that when you start to see things missing you see properties missing and so forth and they just won't render in your template you then know that you haven't actually returned it from the setup method i will warn you of that because it's guaranteed to trip you up so once i have exported out my properties computed methods and so forth what i'd like to do now is actually compose my component a little bit better at the moment we still really haven't improved anything that much so what i want to do is move first name middle name last name closer to the full name for example so i'm keeping code closer together and also the set default method right so what i'm doing here is i'm grouping code together and i'll do the same with the address so this is where it's more important to sort of understand how grouping things together will make it easier to read and clearer to understand now imagine this component was quite a bit more complex than this one this will definitely come in handy i'm not having to scroll up and down the page in this giant object to try and find the property or whatever i'm encapsulating things even further keeping things closer together so that i can discover the code and discover any dependencies or this anything that i'm changing that will change a dependency likewise and vice versa just keeps things nice and simple and of course we've only just scratched the surface here there's many other things such as watched and there's tons of things to ref and reactivity that we have not discovered here but we will be doing in just a moment in this video but right now what i want to do is save that out we've converted our component into this composition api and you'll see that my whole application is still working exactly as expected great the first step is done we've been exposed to what the composition api is we've seen a little bit of the caveats and the benefits a little bit of the drawbacks which is a bit more verbose but it really is a nice little api a cherry on top for vue.js next up we have components and they're life cycle hooks so components have life cycles and as you cycle through life you have moments in your life or key pivotal points well it's the same thing with components they during their lifetime during their existence within your application have certain points and those points will trigger certain things so we need those hooks we need those life cycle hooks at certain points when building our application so the first difference between view two and view three is the before create and created hooks have completely gone those two hooks have actually been replaced by this setup method but then we have the rest of the hooks that we can take a look at so first of all we have to import all of these hooks that will be on before mount on mounted on before update on updated on before unmount on unmounted on error captured on render tracked on triggered so as you can see view three is actually now introducing so much more into the life cycle hooks already some of them you will recognize from view two but there's even more here so now what i'm going to do is the smart thing which is do it all in one go on before mount on mounted on before update on updated on before unmount on on mount on error captured on render tracked on render triggered and i'm going to put all of those hooks into the setup method and then we're just going to log something out to the console now if you still want to access properties and so forth within this component you would use the way that we used the hooks api before where you'd use dot value with ref and with reactive you would just target the property and before we begin looking at hooks what we first want is an analogy to understand hooks a little bit better and it's something you use in your everyday life such as a usb dongle i want you to think of that usb dongle as a view component and your computer as the view library now there's a certain process that follows and certain hooks and functionality that you can hook into in the lifetime of you using that usb dongle with your computer for example you mount that dongle you unmount the dongle and when you mount the dongle you can update information on the dongle and you can cause other things to happen during the life cycle of the use of that dongle so we're going to use that analogy and of course if this were to be a real computer would be like thousands of usb ports everywhere and loads of components or usb dongles being plugged in and out in and out in and out all the time and we can hook into that functionality and do what we need to do as programmers so the first hook was actually created a while ago which was set up now this is when you first push the pen drive into the computer at the moment the computer may not know every single thing about that piece of hardware that dongle you plugged in but what it will do is it will say right that setup hook will be triggered and that is when before all the configurable options and so forth happen right because you're creating those options you're creating properties and reactive properties in the setup hook so this is like at the very earliest stage you can enter into a component you've just plugged it in next up we have on before mount and that will be called right before mounting of the dom begin so before it renders the template what it will do is call before mounted this is great if you want to prepare some sort of data or call some data from a server somewhere and have that prepared before you render the dom for the first time i look at this like now as you plug the usb pendrive and it's got the configurable options it knows what options there are there but maybe we want to do something initially before we mount that pen drive or that component the next one is on mounted this is called when the instance has been mounted so that's when you finally plugged it in and the user can see it pop up on the screen for the first time when that partition is mounted from that pen drive you actually see that partition in your file explorer this is great for them when saying right when we're ready we can then load in some additional data or do some additional actions then we have on before update now this is called when the data has changed so some reactive data such as a property and before the dom is re-rendered so before your templates re-rendered some property has changed um we can hook into that and before i render any sort of update to the user i might want to get or perform an action like that before the user sees anything so that's what on before update does and then on updated well with on updated that's called when the reactive data has changed just like before but the dom has finished rendering so there was a reactive change and also the dom has rendered this time next up we have on before un mount so we've mounted this we've had updated life cycles you know we've updated this dongle but now we want to unmount it well i look at this process as the eject process or the safely remove that pen drive or safely remove this component process now obviously this isn't a requirement where it is with a usb dongle obviously with the before unmount that will go ahead and trigger before the component before that usb is tugged out of the machine so you still have access to the properties maybe you want to very quickly save some of the properties information out to local storage or do some kind of check before you un-mount that component then you have the unmounted hook this hook will trigger as if it were to be that you've actually physically pulled it out of the machine you've removed that entire usb thumb drive you remove the component it's been completely destroyed and then of course view the computer will say aha this guy is completely removed from me he's gone and that's when that hook will trigger which is on unmounted then we have error captured now error captured will be triggered when any of the descending components error and it will be captured at that level and it basically bubbles up so if you think of a bubble a bubble rises an event rises information rises so let's say we have lots of nested components but the parent component will be able to have the error captured and it will capture any errors from its descendants and even those descendants and the descendants of those descendants right it's a whole tree structure then we also have on render tracked so this is called when a reactive dependency whether that be a property in your component is being accessed in the render function during render so if someone's accessing a property during or in the render function it's going to trigger this particular hook this is helpful to see which dependencies are being tracked for debugging purposes most of this will be used for debugging purposes and then you have on render triggered so that is when you've made a change and that has caused the renderer to trigger and it says triggered past tense which means that it's finished triggering that sort of render call so you do on render triggered and then it will call that hook and then you can define your information in there now the final part to this is something that we have to understand about keep alive now you might not have heard of keep alive in view but what keeper live does is pretty much what it says it keeps a component alive and this opens up new hook possibilities such as on activated and on deactivated so let's add on activated and on deactivated and again i can add that once i've imported it into the setup method but let's take a look at a real world example of what keeper live does so in the documentation we can see that in this first instance we have tabs and these tabs load blog posts now each time i click on one of those it's going to mount the blog post component create an instance of that component and then when i click on the next one it's going to unmount that component and then mount the new component now sometimes that isn't very productive sometimes you want to cache your components so in order for you to potentially not load in more data or make initial requests to the server for this blog post for example if it's dynamic maybe you want to store it in cash keep it alive whilst the user's on that page in those tabs so we wrap that in keep alive and now when i click on the blog posts it's not going to just unmount it will mount the first blog post i click the next link now unmounted will not trigger because we're not on mounting we're not destroying that instance we are leaving it in cache and then we're mounting a new component so at the moment the only way i can really trigger something here is with mounted and if i go back to the previous post nothing will trigger not mounted or unmounted even if i go off it because it's still kept alive now if i navigate away from the page yes it will do mounted and unmounted again however during the life of these tabs they are being kept alive in cash that's where on activated and on deactivated come in so when i now have the hooks on there even though the component is kept alive every time i show that component from cache it will trigger on activated and every time i hide that component but it's still kept alive that will then be on deactivated now let's very quickly move on to watches now i didn't want to overwhelm you initially and of course we're learning a ton of things but now it's time to learn about watchers so at the moment we didn't have any watches but let's say we did and we wanted to watch the first name middle name and last name well with the classical way of doing things you would have to write watch and then you'd have to watch the first name then the middle name and then the last name and then of course if you were to write some code to perform some functionality based upon those changes you would have to repeat that functionality three times or you would have to turn that into a method and then call that method in the watches now this is very unproductive it's not nice and it's not clean and the composition api offers a great advantage over the classical model here that really does boost productivity and make us write much cleaner code so the first thing we're going to do is import watch from the view library now that i've imported it i can go into setup and we can create a watcher and then the first argument that i'm going to pass is what i want to watch for so we'll start with one so far so the first thing that i want to watch is first name this second argument is the callback function now the callback function has the previous and then the new value passed in automatically and so we're going to define those parameters and then we're going to create the execution context it's just going to log out to the console and then tell us that the first name has changed and there we're able to see the output so this is really great but it's not really added much advantage on top of the old api but now let's say that i actually want to watch multiple sources like i was before well the first argument will now need to be an array and that array will be first name middle name and last name i can now watch all of those values in one watch function call you can see how this is quite a bit nicer then when fetching the data i can pull that previous and next value out for each one of the watches so i'm watching three properties here and i want three sets of previous and next values again these are optional but i'm demonstrating all the features here so i can look at the previous and next value of name middle name and last name and i just give those parameters names and we go ahead and take a look at that inside of the function and we can even print out the previous and next values in the console print out all of those previous and x values on any one of those and you'll be able to see that when i make a change to either first name last name or the middle name then it will automatically trigger this watcher and we only have one execution context with all of the data that i need and it's very simplistic now hopefully you can see how this is actually far better than what we had before in the classical way of writing components now there's also something brand new out the box called watch effect now i want you to think of this like the computed version of watch so with computed properties whenever you use property it automatically deals with that dependency injection so if i use first name in computed every time i make a modification to the first name property it automatically will trigger that computed property well this is what watch effect is so watch means that you have to explicitly say what you want to watch however watch effect is where if you use some property and it detects that it will automatically detect that as a dependency and then trigger that watch so let's take a look at this now i want to first of all import watch effect from the view library then i want to call watch effect within the setup function then what i want to do is create an execution context create a function and within that function i'm going to console.log out the first name middle name and last name now it's automatically done that dependency injection i don't need to define what i want to watch for the watch effect will say okay my execution context is wanting access to first name middle name and last name properties therefore that is the dependency injection so when i don't need to explicitly define what i'm watching for i can use watch effect basically making it like the computer of the watch world it's automatically detecting dependencies and then triggering this watch effect when those dependencies are changed and of course when you see this in your browser you will be astounded when i change the first middle or last name it goes ahead and triggers that prints it out in the console and hey presto watch effect is now in effect next up we're going to take a look at the ref and reactivity very much in depth but in order for people to really understand what vue is doing under the hood i need to explain proxy objects first what does proxy actually mean what it means is that we are acting on behalf of someone else if someone is acting on proxy you could look at a solicitor is acting on proxy on behalf of the client that he's defending well it's very much the same thing with proxy objects you see you give you your objects but your objects are plain standard javascript objects but what view does is create something called proxy objects so it actually takes your object all of its values and so forth and then it adds this proxy object that will watch for mutations on any one of those properties and so forth this allows view to become reactive whenever you update that string or update that object it will trigger the event and that event will then update the dom and vue does this automatically for you behind the scenes so that you just put in what you want and then vue takes care of the reactivity part of the application so this is what we mean by proxy objects so now that we know about proxy objects the first thing we need to discover is actually how to pull a value out of refs in the composition api uh you cannot just log out the actual reference because that's an object and many people may be going why did i use constant well the proxy object i want to stay constant so when i do the console.log i point to first name and then i do dot value and that will actually pull out the value of that property now if you need to assign a value to that property not the proxy object but the value and then use the assignment operator now let's just say that maybe we're going to pass this data up to a data layer maybe it's a product in a cart and what we actually want is to send the product to the api layer now you don't want to send a proxy object to an api layer that's a proxy object a proxy object is only useful for view but if you want to actually get the value out sure you could point to dot value but however you can use the un ref function as well so first of all import unref and then you can go to the setup function and point to let's say first name and what that will do is it will unreference it will take out the value out of the proxy object it will strip everything out of that reference that's to do with the proxy and just leave the reference itself either as its primitive value or the value that you've given it next up we have the to ref so first of all we want to import that from view and then we want to go into the setup and then what we want to do is to ref allows you to create a reference a proxy reference object that comes from a reactive object so we can see with address this is a reactive object it's a proxy object that wraps an object and it's going to deeply watch all those properties and it will update so to reference allows us to pull out a property from for example address a reactive object pull out let's say line one and have that as a separate reference but it keeps the link to the reactive object so i'm going to create a new property called line one then what we need to do is export that using the return object of the setup method we go up and now to prove that it maintains its reactivity we're gonna change the v model of the address line one to the new line one property so now when i save this and i modify address line one notice how that v model is actually assigning back to the line one property however when i update it you'll also see the address objects property line one also updates so we're able to create almost like an alias or sim link to our properties within reactive objects the next one is is ref isref can be imported again from view and then this is actually really simple you pass it in a argument and it will determine if that argument is maybe a standard value so it's not reactive it will return false if it returns true it means that it is a reactive object it's a proxy object now even though it's recommended to use reactive you can actually use an object with reference now when you use an object it will deeply watch and this is by default with view view always wants to deeply watch all the nested properties so if you've got objects inside of objects inside of objects it's going to wrap each one of those objects with a proxy object now this adds to memory consumption it has the power consumption everything you do that adds to the operation of anything is going to have a knock-on effect and with the old way of doing things the vue 2 way you had no control over that it would always do that but what we would like to do is potentially control this to the point where we don't really want to nest all of the embedded objects with proxy objects however if i actually update anything within it in that shallow reference that isn't triggering a re-render and watch effect won't trigger because it's not a deeply referenced object it's just watching dot value but anything inside of dot value that object it's not going to trigger therefore watch effect will not trigger so let's just say for argument's sake i had really big objects and i didn't really want to make it all deeply reactive however when i do make changes to shallow reference objects then maybe i want to trigger an update and that's where trigger ref comes in so all you've got to do is first of all import the trigger ref from the view library and then you want to do trigger ref and then pass it the shallow reference that you created that property and then it will actually trigger that reactive change that we're looking for so the next thing is looking at reactive and we can basically just take a lot of the knowledge we've just learned from refs and then move that over to reactive so first of all reactive we've already used with the address object so reactive is basically taking an object and then making a replica of it by default again it's deeply proxied so you can tell by the fact we've got shallow reactive and so forth that we can get rid of some of that reactivity if we don't need it which is another benefit of this api over the view 2 api we get to control what's reactive so in this case we passed it an object and it created a duplicate now you can also create read-only objects read-only objects are actually really good potentially in methods or in something that you might not want to create adverse changed effects on so read-only is pretty good all you've got to do is create it and then say read only and then pass it the original object so this will be the address object in this instance and what it will do is it will make sure that it's all still reactive everything else but it's read-only so you can't go in there and start affecting things if you do you will get a warning it's pretty much self-explanatory it's creating a read-only instance of the prior reactive object now if the original object is updated such as the address and if that object updates the read-only one will also stay up to date with the original object it's just that you can't modify the original object with the read-only instance next up is is proxy and is reactive i mean this is pretty much two birds with one stone here is proxy we'll check to see if it's actually a proxy object which we now know what that is and also you have is reactive now is reactive will say is that particular value is that particular property it could be a deeply nested property and so forth is that particular property reactive will it react if i update it so these are nice checks to see whether there's reactivity on something you're about to update next up is read-only which again is self-explanatory you pass an object and it basically says is that a read-only object that was created with the reactive api the next one is to raw so what to raw will do is it will strip out the proxy object just like with the ref you could send it to its raw functionality basically so you're stripping out all of the proxy stuff and you're just returning the raw object that you initially inputted and it will get rid of everything else next up is mark raw now mark raw is actually really important because sometimes and i've had instances of this where you don't want to create a deeply watched object you just don't want it it's not necessary so mark raw will make sure that throughout the entire application's life span and use of that particular value that you passed into mark raw it will never be allowed to be turned into a proxy object it won't allow that to happen so that is why mark raw is really good even if you try to put that inside of a reactive object even deeply nest it inside of a reactive object it will not make that reactive raw is raw it says it's raw javascript it's the raw value that i've given it i never want you to turn that into a proxy that can be actually very useful and finally we have shallow reactive which you can imagine what that will do just like with shallow ref so with shallow ref it only watch the value property but if i gave that value property an object for example it wouldn't try to deeply proxy that well it's the same thing here so i can have address for example and if i make that shallow reactive there won't be actually any difference it will still watch all of the properties but only on that shallow level only one step in right but when we start going more nested so let's add an object into the address now that object that i've just created the key that holds it if i assign a new object to that key or a new value whether it be a string or whatever that will be reactive however everything that's nested inside of there that's deeply nested that's not going to be proxied it's not going to be converted into a proxy object because it's a shallow reactive this can actually be again really great for trimming out unnecessary calls unnecessary render triggers we want to keep things down to a minimum when it comes to reactivity so that only the things that really need to be reactive will be reactive and then the final one is shallow read only which you can only imagine what that one is so we're creating an instance a proxy object on the main one just like shallow reactive where it'll only look at those very shallow keys but anything nested any nested keys and nested values they will not be reactive and they won't be watched and this time it's read only so you can pass it in a previous object or you could create a new object with shallow read only it's up to you and it will only allow you to read it it will not let you do anything else and as i said again it will only be reactive on those very shallow keys the nested keys it will not react to and even if the original changes and let's say the original is a fully reactive object the shallow read only will not react to deeply nested changes so if there's any changes on the shallow keys it will update the shallow read only if you've created a duplicate copy but it will not trigger anything if you've got a deeply nested key from the original object and even if that's deeply watched the one from shallow read-only will not be triggered and with the setup lifecycle hook you will notice that we can also pass in two parameters we can define those parameters the first one will be the props so if you have props coming in from a parent component to your component this one on this level then you can go ahead and use props and the second parameter will contain the app context this is useful for a number of things such as attributes or attrs emit if i want to emit something up expose and slots so we have access to all of those things with these two parameters next up we just want to use the view x store so i'm not going to go too much into view x but that's where your application state exists you can do this by importing the use store from view x once you've imported that all you need to do in your setup function is i would create a constant called store and then just call you store this will give you access to the state of the application all of the modules and also the dispatch method and also if you wanted to map the getters and so forth then i would just do it the traditional way because don't forget that this is just a complimentary api and so what i will do is just basically create computed on the normal way i would do it and then i would just map the guesses in there like i normally would with view two and that way everybody's a winner you can still map all your getters it doesn't have to all be this brand new api but if you start implementing it and influencing yourself with that new api i guarantee you that at some point it was going to benefit you especially in large scale applications where logic does start to creep out and get rather complex rather quickly and you'll find that mostly in the e-commerce sphere all right guys thank you for watching this video and to summarize we've taken a look at all of the new view 3 api such as refs reactive view x and all of the hooks that's involved with the brand new view three api alright guys so i hope you've enjoyed this video hit that subscribe button and join the avalex family it will be much appreciated and then also join the newsletter which is also linked in the description down below so that you can get the source code of these videos quick and easy and also jam-packed with more developer content and free goodies so thank you for watching and if you'd like to watch some more stuff go ahead and take a look at these courses above me and take a look at the latest stuff that we have to offer
Info
Channel: Programming With Avelx
Views: 2,141
Rating: undefined out of 5
Keywords: Computer Programming, Avelx, vue composition api, composition api, vue 3, vue 2, vue 2 vs vue 3, vue 2021, vue 3 tutorial, vue 3 composition api, vue 3 typescript, vue programming language, Academind, Vue, Vue3, Vue.js 3, Vuejs 3, Vuejs3, Vue 3 tutorial, vue 3 comparison, composition api tutorial, free vue, free vue js course, maximilian schwarzmüller, maximilian schwarzmüller react, Vue hooks, Convert to composition API, Proxy Objects, Component lifecycle hooks
Id: Pajw6WBeWr4
Channel Id: undefined
Length: 42min 42sec (2562 seconds)
Published: Thu May 13 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.