Vue Composition Api Methods

Posted on  by admin

📌 Note: Auth0 doesn't yet support Vue 3. This tutorial is just a look at using the Composition API in a simple application without authentication.

A common issue that new developers run into is figuring out where to begin. You do tutorial after tutorial to learn a new concept, but once you complete a tutorial, you're left wondering, " what"? In this tutorial, you'll build a project idea generator (inspired by this tweet). You'll be able to use the final application to select the skills you want to work on and be given project idea suggestions based on those selections.

The primary purpose of this tutorial is to learn how to use the Vue 3 Composition API, but the project generator will be a fun side effect. The tutorial will cover:.

Two-way databinding with v-model

Calling an Express API with Vue 3. Using the Composition API in Vue 3. Advanced JavaScript array filtering.

  • Using filters in Vue 3. I'll assume you have some basic Vue 2 knowledge but are new to Vue 3. If this is your first time using Vue and you feel you need some background, check out my Beginner's Vue.js Tutorial.
  • You can find the final project in this GitHub repository. 🚀 Let's get started! First, you need to create your Vue project.
  • I like to use the Vue CLI to get up and running quickly. You can create a new project with the CLI by running:. If you already have the CLI, make sure your running at least v4.5 so that you can use Vue 3. Choose the options shown below. 👩‍💻 Tip: Press spacebar to select an option and enter to submit once you're done selecting.

For features, select "Choose Vue version", "Babel", "CSS Pre-processors", and "Linter / Formatter". Now you'll wait a minute for the CLI to generate your project. Once it's done, switch into the project folder and run it with:.

Composition API vs Options API

And your starter application is now running on http://localhost:8080! Open up the project in your code editor. 👩‍💻 Tip: If you're using VS Code, install the Vetur extension to get syntax highlighting, Emmet shortcuts, formatting, auto-completion, and more.

For simplicity, you're going to just keep everything in one main component called Generator.vue. You'll notice at the end that some of this can be refactored out into separate components, but to keep this tutorial focused on the Composition API, you can save refactoring for later. Rename the src/components/HelloWorld.vue component to src/components/Generator.vue and replace its content with a barebones Vue component:.

Next, open up src/App.vue and replace it with:. Here, you're just pulling in the Generator component. There's nothing in here yet, but once you start adding to the component, the base App component is already set up to display it.

Finally, in src/assets, delete Logo.png. For basic styling, you're going to use Bulma, which is an open-source CSS framework. Run the following in your terminal to install it:. Next, you need to import it into your Vue project.

Create a new file under src/assets called main.scss. Here, you just need to import Bulma. Now, bring that main.scss file into your Vue templates by opening src/main.js and updating it with:. This should leave you with a simple base Vue application.

And this is where the real fun begins!

One of the big features that the Vue 3 release brings is the Composition API. In Vue 2, components were built using the Options API. The CodeSandbox below shows a very simple component using the Options API.

The setup option

Component with Options API. In Vue 3, in addition to the Options API, you now have the option to use the Composition API.

  • Below is an example of the exact same component, but using the Composition API instead.
  • Component with Composition API. You'll notice the big difference here is the setup function.
  • This is a new component option that holds all of the logic for the component.
  • Instead of defining data, methods, and lifecycle hooks as separate component options, all of these now lie in the setup function.
  • Another important difference is that you no longer have to use this to access your data in methods.
  • This change has allowed for much better Typescript support in Vue 3. Let's see the Composition API in action by adding to the Generator component that you created earlier.

Replacing the methods option with functions

Here's what this component should do:. Call the Express API (will be provided) to grab the list of skills that can be used in the generator. Display the list of skills. Allow the user to select the skills they want to work on.

Call the Express API to get the list of application ideas. Display the application idea options based on the skills selected. Create a filter to select a random option from the app list. First, clone the Application Generator API repository to get the Express API. List of skills: http://localhost:3000/skills. List of applications: http://localhost:3000/apps. You'll be working with the data shown here soon, so you can leave these tabs open if you'd like to reference the data structure throughout the article.

Next, open up src/components/Generator.vue. The first item on the agenda is to call the Express API to get the list of skills.

Let's do that now. Replace the section with the following:.

So what's happening here? First, you're importing ref. This allows your data to be reactive. In other words, you can use this data in your template, and if it changes, the template value will change as well.

Inside the setup function, you'll see that skillList is declared as an empty array wrapped in ref(). This returns a reactive ref object with just one property: value. The .value property points to the inner value of the ref object, which in this case, is the empty array.

Next, in the getSkillList function, you're making a request to the /skills endpoint of the Application Generator API. skillList is set to the response that comes back. You should notice here the use of the .value property mentioned above.

This is how you access and set the value of a ref. Finally, you need to return any data you want to expose to the template. So far, that's just skillList. The next item on the agenda is to display the list of skills. Let's do this now so that you can see how skillList can be used in the template.

Update the and sections as follows:. Here, you're looping over the skillList array and setting up a checkbox input next to each skill. There is also some simple Bulma styling here. Next up, you need to allow the user to select the skills they want to work on. You've already laid the foundation for this by setting up the checkboxes and setting the value to the id of the selected skill.

Replacing the data option with ref()

However, the checkboxes currently aren't bound to anything, so nothing is really happening.

To fix this, add a new ref in the setup function called selectedSkills, and set it to an empty array.

Make sure you also return it so that it can be used in the template. Then, update the template to bind the checked boxes to selectedSkills using v-model.

To confirm that it's working, you can temporarily add the following to the template:. Select some skills, and you should see an array displayed that holds the ids of the skills that you select.

Once you confirm that's working, go ahead and remove the last line. Next up, you need to grab the list of application ideas from the Express API.

This will look similar to the API call that was made earlier to get the skills list. Add the following to your setup function:. Do you notice anything different here? Take a look at how appList is declared. It isn't using ref()! Because this value isn't being exposed in the template, you don't need it to be reactive. The purpose of this list is to be the main source of possible applications that the user can build. Because the user is going to be filtering the list based on what skills they want to work on, you're also setting up the filteredAppList array. This array needs to be reactive because it's going to be displayed in the template.

As soon as the user clicks on a skill, this list will need to be updated to show which applications include that skill. You're setting it to include all applications before the user selects anything. This leads to the next action item: displaying the application options based on the skills that the user selects.

Watch API with ref

The filtering required to get the final application list is going to get a little complicated, so let's walk through the logic first. The goal of this function is to generate the filteredAppList array. This will hold all the possible application suggestions that contain the skills that the user selected. You're going to create a function called generateFilteredAppList() that will do the following:.

Loop through the main application list. For every application, check if the selected skills array is a subset of the application list's skills array. If that application contains all of the selected skills, then add it to the new filteredAppList array. To envision this better, remember what the data looks like:. In this case, filteredAppList should be { id:4, app:'a blog', skills:[1,3,5]} because that is the only application that contains all of the selected skills. Update setup as follows:.

First, you're looping through every item in the appList array.

  • For each item, you're checking if the all the selected skills are contained in that application's skills array.
  • This is done by combining Javascript's .include() and .every(). .every() — The every() method tests whether all elements in the array pass the test implemented by the provided function.

Handling props

It returns a Boolean value. .includes() — The includes() method determines whether an array includes a certain value among its entries. It returns true or false. For every application option, you're running it through the checker function, hasAllSkills(), which returns true or false.

If the value is true, then you push it onto the filteredAppList array. Make sure you also create the filteredAppList ref and include filteredAppList and generateFilteredAppList in the return object.

Vue 3 Setup

Now that you've gotten through that fun filtering function (😅), it's time to display it in the template!

Update your template as follows:. Here, you're looping through the filteredAppList to display each skill that the application utilizes. You're also showing the resource link that is included for that skill. You'll notice though, when you click on some checkboxes, nothing happens.

Replacing the provide & inject options with provide() and inject()

That's because you're never calling the generateFilteredAppList function. Update the input to call generateFilteredAppList whenever any checkbox is clicked:. Now, if you click on some checkboxes, you should see the application options updating immediately!

You can fix the card styling by adding the following to the component styles:. This brings us to the final item on the agenda: create a Vue filter to display a random option from the skill list for each application option. You want to give the user as much direction as possible, so instead of just listing the skill, you're going to include what service or resource they should use to accomplish it.

Introduction to the Watch API

So, you need to pseudo-randomly grab one of the skill options and display it. So how do you do that? Well, it's a bit of a trick question.

Here's the problem: filters were removed in Vue 3! In Vue 2, you could create a filter and add the pipe symbol to use it in your template, like this:.

Since this functionality was removed in Vue 3, it's recommended to just create a method instead and call that in the template. This is what the data for the skillList looks like:. For the selected skill, you need to look into the options array and randomly pick one of the items.

Update setup as follows:. Next, back in the template, update the skill list as follows:.

  • And then add the last of the styles:. Because you need to use the random value twice (for the link and to display the skill), you're going to have to use a little "trick" here.
  • You're creating a temporary local value that holds the current return value of getRand() for this spot in the for loop.
  • And that should do it! Take a look at your final application, and you should now be able to filter through to find the perfect app to test your skills.
  • Phew, that was.. Let's recap everything that you just learned. How to use the Vue 3 Composition API.

Lesson Project

How to call an API using Vue. Advanced list filtering in JavaScript. How to use filters in Vue 3.

  • How to use Bulma with Vue. Feel free to modify the Express API to add some more skills and sample application options that interest you. If you end up building any of the practice applications, tweet me and let me know!
  • And if you have any questions, be sure to leave them down below. Thanks for reading! In this Vue tutorial we learn a different way to write component logic with the Composition API.
  • We cover how to move to the new setup option and how to replace options from the Options API with their new function counterparts. Replacing the data option with ref().
  • Replacing the watch option with watch(). If you want to follow along with the examples, you will need to create an app generated by the Vue CLI. As mentioned in the Vue API lesson, the Composition API combines all of a component’s data and functionality into a single section.

Watch API with Reactive

Instead of separating our code into different options likedata,methods,computedetc.

we now use only thesetupoption. The Composition API’s only focus is changing how the data, methods, watchers and computed options of a component can be written differently.

Instead of using separate options, they are now bundled into a newsetupoption.

The option takes a function as a value, so we can use the ES6 shorthand syntax and simply write it assetup().

Vue executes the function before the component is created, before any lifecycle hooks.

Custom events and context

As an example, let’s log a message to the console insetup, as well as thecreatedandmountedhooks.

The console output from the example above shows the order of execution. noteBecause setup is called so early in the lifecycle, the component hasn’t been initialized yet and this doesn’t reference the config object like we’re used to.

We don’t use this in the setup option. Thesetupoption takes two optional arguments. Data that’s passed down from a parent component. A Javascript object that exposes 3 different component properties. To access data from the function in the components template, we return that data at the end of the setup option as an object (like we did with the data option). When a key has the same name as its value, we can use the ES6 shorthand syntax. noteThe data we returned above is not automatically reactive like it is in the data option. We have to manually do it with reactive refs. If we want to make our returned data reactive, we use thereffunction.

The function is imported from the ‘vue’ package and takes the data we want to make reactive as an argument.

If we want the data to be available in the template, we have to return thereffrom thesetupoption (like we do with thedataoption).

If we want to access the value of arefinside thesetupoption, we have to use thevalueproperty. As an example, let’s create arefwith a simple greeting message that we return and output in the template. We’ll also access the value in a timer inside setup and change its value after 3 seconds. Arefdoesn’t have to be a primitive value, like a string or a number. We can use objects as well. If we want to access it insidesetup, we have to use thevalueproperty again, followed by the object’s key.

If we expose the object’s properties outside of the setup option, they lose their reactivity. They will display fine in the template, but they won’t update when the timer executes.

We have to expose the whole object, not the separate properties. As mentioned earlier,refcreates a wrapper object when we pass single primitive values to it.

Replacing the computed option with computed()

In Javascript, primitives are passed by value, not by reference. Wrapping values in an object helps keep the behavior unified across different data types.

So having them in an object allows us to safely pass it across the app without having to worry that the data will lose its reactivity. Thereactivefunction is likerefbut it can only take objects, not primitives. One benefit ofreactiveis that we don’t need to use thevalueproperty to access the object’s value. Butrefhas thevalueproperty for reassignment,reactivedoesn’t and therefore cannot be reassigned.

As we mentioned earlier,reactivecan only receive objects and cannot be reassigned so it’s use is limited.

Butrefcallsreactivein the background, so in some cases you might want to avoid the overhead from the extra step and usereactiveinstead ofref. When you have primitive values (number, boolean, string etc.). When you have an object you need to reassign later (like swapping an array for another).

When you have an object you won’t need to reassign and you want to avoid overhead ofref. We userefexclusively simply because sometimes usingvalueand sometimes not can be confusing. We prefer the consistency of always usingref. Many other developers also prefer only using ref, and some even considerreactiveto beharmful.

Wrap Up

With the Options API we define custom functions in an option calledmethods. With the Composition API, we define functions directly insetup. The functions can be regular Javascript functions, anonymous functions or arrow functions. Like data, we have to return a function from thesetupoption if we want it to be available in the template. As an example, let’s create three functions that change the value of arefwhen the button they’re bound to is clicked.

Further Reading

Ivaylo Gerchev

I am a web developer/designer from Bulgaria. My favorite web technologies include SVG, HTML, CSS, Tailwind, JavaScript, Node, Vue, Nuxt, PHP, Laravel, and Statamic. When I'm not programming the Web, I love to program my own reality ;)

What is the Composition API?