Reader small image

You're reading from  Building Real-World Web Applications with Vue.js 3

Product typeBook
Published inJan 2024
Reading LevelIntermediate
PublisherPackt
ISBN-139781837630394
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Joran Quinten
Joran Quinten
author image
Joran Quinten

Joran Quinten's passion involves getting people to love technology and getting technology to play nice. With over a decade of experience in developing and designing software, he has built up a broad background in development and architecture. He loves sharing knowledge and has been invited to speak at several tech events. Joran graduated from Fontys University of Applied Sciences, Eindhoven in 2010. Currently, he works for Jumbo Supermarkten, a national grocery chain where he is the technical lead of the design system team and acts as an ambassador for the tech department. He is passionate about mentoring and coaching junior developers. Joran lives close to Eindhoven with his wife, son and daughter.
Read more about Joran Quinten

Right arrow

Creating the Marvel Explorer App

Let’s build an app that’s a bit more advanced, using a third-party API to feed it with data. I hope you like comics, because we will build an explorer on the Marvel Comics API, and I will try to squeeze in some heroic puns. We’ll explore adding different routes and add a bit of abstraction to make better use of writing our code.

We’ll cover the following topics in this chapter:

  • Getting started
  • Retrieving data from the API
  • Routing in a single-page application
  • Writing and using composables
  • Searching for and handling data
  • User-friendly error handling

Technical requirements

In this chapter, we’ll replace node package manager (npm) with performant npm (pnpm): https://pnpm.io.

We need to register at https://developer.marvel.com/ to retrieve an API key. We’ll add Tailwind CSS (https://tailwindcss.com/) to apply styling to this app as well.

In this chapter we introduce routes using the official router for Vue.js applications: https://router.vuejs.org/.

The complete code for this chapter is available at https://github.com/PacktPublishing/Building-Real-world-Web-Applications-with-Vue.js-3/tree/main/04.marvel.

Getting started with our new project

In order to get started, we need an API key. If you go to https://developer.marvel.com/ and select Get a Key from the menu, you will need to register for a free account. Afterward, you will be redirected to the developer portal, where you create a key to interact with the API. Make sure to note the public and private keys.

For our example, we will access the API from localhost, so you need to add localhost and 127.0.0.1 to the list of authorized referrers.

Note

If you want to deploy this app to the web, you will need to make sure to add the corresponding URL of the app’s address there as well, but the deployment step is not covered in this chapter.

I’d like to point out the documentation, which you’ll find under Interactive Documentation. I recommend playing around with it for a bit to get a sense of our data provider.

Let’s start a new project!

npm init vue@latest

Hit y to proceed, choose vue-marvel...

The Superhero connection

We want to retrieve data from the Marvel Comics API from different components in our application. A good pattern for doing this is by creating a Vue composable. A Vue composable is a proven pattern for using and reusing logic throughout your application. We’ll create a folder called composables in the src folder and create a file called marvelApi.ts.

You can import the types from the example repository (https://github.com/PacktPublishing/Building-Real-world-Web-Applications-with-Vue.js-3/blob/main/04.marvel/src/types/marvel.ts).

These types are mainly contracts with the API. Feel free to take a look at them. I created them by ingesting the results from the API and defining the types.

We’ll start with an asynchronous function that fetches the data from the API from the comics endpoint and returns a promise of the response. We’re going to expand the functionality gradually. Add a new composable function called useComics to the file...

Marvelous routes in a single-page application

Now, let’s take a look at the default setup of the application, because we’ve pre-installed the app to use vue-router. This configured the app with a couple of things:

  • We have an index.ts file in the router folder
  • In the views folder, we have two components called HomeView.vue and AboutView.vue
  • In App.vue, we have some components called RouterLink and RouterView

That’s how routes are tied together. Let’s take a look at each of them.

The contents of the router folder define and configure the routes for the application. Routes define the different paths in your application and the components that should be rendered when those paths are accessed. Each route is represented as an object with properties such as path, name, and component.

The path property specifies the URL path, and the component property specifies the Vue component to render. The name is not required and more meant as...

Composables, assemble!

Let’s take a look at how we can leverage our composables and refactor the app to expand the functionalities a bit. Composables are all about reusability: it’s their superpower in the Vue space, so let’s put our previously created composable into action.

First, we will work on refactoring the useComics composable, where we will lightly apply the clean code principles. In our context, this will translate to applying the single responsibility principle and writing small and cohesive functions with meaningful names.

Refactoring useComics

We’ll refactor in a non-destructive way too, leaving the existing useComic composable functional until we’re ready to update that too.

We’ll first move the static constants out of the function to the upper scope. We’ll also import additional types that we will reference in functions. This way, we can still access them, but they are available throughout the file. I make...

Managing the roster

With our brand new composable, we have easy access to more data from the Marvel Developer API! We’ll move onto creating the Vue components that will allow the user interface to deal with searching.

We’ll first create a variant of the ComicCard.vue named CharacterCard.vue. The component will be a bit simpler, so you can either paste the following contents in the file or create a copy of the ComicCard.vue and update it to match the contents:

<script setup lang="ts">import type { Character } from "@/types/marvel";
import CardView from "./CardView.vue";
interface Props {
  character: Character;
}
const props = defineProps<Props>();
</script>
<template>
  <CardView :id="character.id">
    <img :src="`${character.thumbnail.path}.${character.thumbnail.extension}`" class="float-left w-12 h-12 mb-2 mr-4 rounded-full shadow-md...

A different vision

At this point, our app is functioning just fine. We can improve our app experience by making sure we can handle situations when the API returns an error. Let’s see how we can make our app a bit more robust in that sense.

We’ll add a page that will be able to display errors to the user when they occur. Let’s start with a new file in the views folder called ErrorView.vue. Just create a template with the following contents:

<template>  <main>
    Oops!
  </main>
</template>

We’ll circle back to this file later. We can now at least create a new route in the router/index.ts file, which just duplicates similar logic from the search route:

import { createRouter, createWebHistory } from 'vue-router'import HomeView from '../views/HomeView.vue'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes...

Summary

In this chapter, we’ve learned how to add multiple pages and navigate by several means: by using the router-link component or manipulating the routes programmatically. We’ve created composables in order to use and reuse logic within our application. For a better user experience, we learned how we can handle errors in a user-friendly manner.

In our next chapter, we’ll build an application using Vuetify, a third-party component library. Component libraries allow us to speed up development by making use of ready-made components. In addition, we’ll introduce an application state using Pinia, where we can modularly store data (or a state) to be shared between components throughout our application.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Building Real-World Web Applications with Vue.js 3
Published in: Jan 2024Publisher: PacktISBN-13: 9781837630394
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Joran Quinten

Joran Quinten's passion involves getting people to love technology and getting technology to play nice. With over a decade of experience in developing and designing software, he has built up a broad background in development and architecture. He loves sharing knowledge and has been invited to speak at several tech events. Joran graduated from Fontys University of Applied Sciences, Eindhoven in 2010. Currently, he works for Jumbo Supermarkten, a national grocery chain where he is the technical lead of the design system team and acts as an ambassador for the tech department. He is passionate about mentoring and coaching junior developers. Joran lives close to Eindhoven with his wife, son and daughter.
Read more about Joran Quinten