Getting started with Vue.js 3 by building a Pokemon search application

TL;DR

In the previous tutorial I showed you how to get started with Vue.js 3 by building a Giphy search application. That was a long while ago 🙂, so here's a new and updated post.

But, to not just update the post, I decided to do something different. Since my kids are into Pokemon, what better use of my coding skills than to make them an app where they can search for their favorite Pokemon and check their stats.

So, in this post, you'll learn how to use create-vue (official Vue project scaffolding tool) to build a Vue.js 3 application for searching Pokemon by using Poke API.

Introduction - The Battle is Over Indeed

A few years ago, this was a popular meme. It was funny because it was true 🙂

However, it seems that the craziness has settled down a bit and that the war is seemingly over. For now. These top four (top 5 lists are overrated 😉) frameworks established themselves:

I added the number of Github *s (at the time of this writing), but I don't want you to read into that too much 🤗

Analysis paralysis will, well, paralyze you!

You could argue that there are other options like Ember, Mithril, or good 'ol jQuery even! However, this tweet says it all:

Developers are fighting over which frontend framework is better.. it's not like users know or care. They mostly care about the User Experience. UX should be our focus on the frontend.

Personally, I stuck to the Angular bandwagon since version 1.0, but that started losing its ooomph after versions 2, 3, 4, ... sorry, lost count.

I believe that Vue.js (due to its progressive and flexible nature) is a perfect fit for teams that have to rewrite old codebases one step at a time. However, you can also use it as a full-blown framework if you wish.

Personally, React's JSX just seems wrong, and some people, smarter than me, swear by that being TheRightWay™, and I guess we're not here to discuss tastes...

Recently I checked out Svelte and kinda like it, so will be doing a post like this for it; stay tuned.

General 'framework war' kind of questions I tend to answer in the following way:

Please just stop with the analysis paralysis already.

Do your research, pick a framework (any framework for that matter) that the community is using, use it, and see how far it gets you.

All these talks about X being slow or Y being better just make no sense until you try it yourself for your use case and preference.

Besides, nowadays speed will not be a deciding factor among the top JS frameworks.

With all this out of the way, fasten your seatbelts, take a venti (or trenta) sized cup of coffee, and let's go do something practical! 💪

The Demo App

As said in the intro, we'll build an application for searching (and showing) Pokemon by using Poke API.

You can fork the complete source code on Github.

I'm using Vue.js 3, and I'll be referring to it as just Vue in the rest of this post.

Prerequisites

Make sure that you have the following tools installed:

Start a new app with create-vue

To start the project, run the following command (in your Terminal): npm create vue@latest

This command, as their docs say, will install and execute create-vue, the official Vue project scaffolding tool. You will be presented with prompts for several optional features such as TypeScript and testing support (I named the project PokemonSearch_Vue3):

✔ Project name: … PokemonSearch_Vue3
✔ Package name: … pokemonsearch-vue3
✔ Add TypeScript? … No / Yes
✔ Add JSX Support? … No / Yes
✔ Add Vue Router for Single Page Application development? … No / Yes
✔ Add Pinia for state management? … No / Yes
✔ Add Vitest for Unit Testing? … No / Yes
✔ Add an End-to-End Testing Solution? › No
✔ Add ESLint for code quality? … No / Yes

Scaffolding project in /Users/Nikola.Breznjak/Development/Web/Vue/PokemonSearch_Vue3...

Done. Now run:

cd PokemonSearch_Vue3
npm install
npm run dev

In the previous blog post, we used Vue CLI. That has been deprecated and create-vue is now the default. The reasons that they quote are:

Vue CLI is based on webpack, while create-vue is based on Vite. Vite supports most of the configured conventions found in Vue CLI projects out of the box, and provides a significantly better development experience due to its extremely fast startup and hot-module replacement speed. Learn more about why we recommend Vite over webpack here.
Unlike Vue CLI, create-vue itself is just a scaffolding tool: it creates a pre-configured project based on the features you choose, and delegates the rest to Vite. Projects scaffolded this way can directly leverage the Vite plugin ecosystem which is Rollup-compatible.

You can learn more about 'why' Vite here.

Running our scaffolded project

Let's run the commands (in terminal) noted in the previous output:

cd PokemonSearch_Vue3
npm install
npm run dev

You should get this output:

 VITE v5.0.12  ready in 175 ms

  ➜  Local:   http://localhost:5173/
  ➜  Network: use --host to expose
  ➜  press h + enter to show help

You should see the following page in your browser if you open http://localhost:5173.

Folder structure

Now, let's open this project in the editor of your choice (I'm using Visual Studio Code + Volar extension), and you should see something like this:

This is an introduction tutorial, to get you running fast, so I won't be going into any specific details and will be only focusing on the src folder.

Add content

OK, so let's add something to our app.

But, where to start? 🤔

Well, one of the first things I do when I come to a project for the first time is to look at the generated output. Then I try to find the strings corresponding to that output within the source code.

So, if you search for the string You did it!, you'll see the string is within the App.vue file. This file contains the following code:

<script setup>
import HelloWorld from './components/HelloWorld.vue'
import TheWelcome from './components/TheWelcome.vue'
</script>

<template>
  <header>
    <img alt="Vue logo" class="logo" src="./assets/logo.svg" width="125" height="125" />

    <div class="wrapper">
      <HelloWorld msg="You did it!" />
    </div>
  </header>

  <main>
    <TheWelcome />
  </main>
</template>

<style scoped>
header {
  line-height: 1.5;
}

.logo {
  display: block;
  margin: 0 auto 2rem;
}

@media (min-width: 1024px) {
  header {
    display: flex;
    place-items: center;
    padding-right: calc(var(--section-gap) / 2);
  }

  .logo {
    margin: 0 2rem 0 0;
  }

  header .wrapper {
    display: flex;
    place-items: flex-start;
    flex-wrap: wrap;
  }
}
</style>

Without knowing much about Vue.js, you can see where you would change the You did it! text. So, let's change that to Welcome to Pokemon Search. Save that, and voila!, you'll see the change reflected immediately in your browser.

Add some style

I borrowed the image (hope they don't mind) from Wikipedia and saved it in the assets folder as logo.webp, added a search input, and styled it a bit to match it with the Pokemon style. In case you're wondering, I asked ChatGPT to help with coming up with the style 🙂

Here's the final code that I came up with in App.vue:

<template>
  <header>
    <img alt="Vue logo" class="logo" src="./assets/logo.webp" />
  </header>

  <main>
    <div class="search-container">
      <input class="search-box" type="text" placeholder="Search..." v-model="searchTerm">
    </div>
  </main>
</template>

<style scoped>
header {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.logo {
  margin: 0 2rem 0 0;
}

.search-container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  gap: 10px;
}

.search-box {
  width: 30%;
  height: 50px;
  font-size: 1.5em;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin: 40px 0;
  text-align: center;
}

Also, I did a few other smaller things:

  • added background: linear-gradient(to right, #FDDF3C, #3B4CCA); in the base.css file in the body tag
  • removed the main.css file altogether
  • imported base.css in the main.js file instead of main.css
  • removed the whole components folder

The way this looks now is as follows:

If you get stuck in any of the above steps, please reach out in the comments, and I'll be happy to help.

Pokemon API

Finally, we come to the cool part 🥶, and that is to fetch some data from the PokeAPI and show it in our app.

How do we get this API? Well, if you do a simple Google search for pokemon api and open the first link, you'll also get to the documentation for their API.

By looking at the docs, you can find that the API endpoint that lists all the available Pokemon is this: https://pokeapi.co/api/v2/pokemon. There's a total of 1302 records.

Now, fetching all this data every time you load your app would be a bad idea from the performance standpoint, but also from their fair use policy.

So, what we will do is open this link which will fetch all 1320 Pokemon endpoints. The output looks something like this:

Now, save this output (just Command + S or Ctrl + s if you're on Windows) to a local file that we'll name pokemonapi.json and place this file in the src/assets folder.

⚠️ I just want to give proper props to PokeAPI for their awesome service 👏

For our demo purposes, this will be fine, but if you'd like to deploy this somewhere where you'd get a lot of traffic (or, if the main list of Pokemon changes), you'd have to cache the responses. We'll tackle this in another blog post, but just something to keep in mind.

Show the data

Now we'll want to list all the Pokemon that we have in the saved pokemonapi.json file. To do that, we'll write some Javascript code in the top of the App.vue file that looks like this:

<script>
import pokemonData from './assets/pokemonapi.json';

export default {
  data() {
    return {
      pokemonList: pokemonData.results,
      searchTerm: '',
      selectedPokemon: null
    }
  },
  computed: {
    filteredPokemonList() {
      return this.pokemonList.filter(pokemon => pokemon.name.includes(this.searchTerm));
    }
  }
}
</script>

filteredPokemonList function returns the list of pokemon that we loaded from the pokemonapi.json file and filters them by what we enter in the input box.

And we'll add this portion of HTML just below the search box:

<ul>
  <li v-for="pokemon in filteredPokemonList" :key="pokemon.id" class="pokemon-item">
    {{ pokemon.name }}
  </li>
</ul>

And, we'll add a bit of CSS:

.pokemon-item {
  float: left;
  margin: 10px;
}
.pokemon-item a {
  color: #000;
  text-decoration: none;
  font-size: 16px;
  transition: color 0.3s ease;
  text-transform: capitalize;
}

.pokemon-item a:hover {
  color: #3B4CCA;
}

ul {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 5px;
  list-style: none;
}

Doing this, you should have your app look something like this:

Get additional details about each Pokemon

If you open any of the URLs that you see in the pokemonapi.json file, you will get something like this:

To show some additional information about a certain Pokemon (once clicked on its name in the list), we'll update the li item by adding the a link to it like this:

<li v-for="pokemon in filteredPokemonList" :key="pokemon.id" class="pokemon-item">
  <a href="#" @click="showPokemon(pokemon.url)">{{ pokemon.name }}</a>
  </li>

On the click event we attached the showPokemon function (by using @click) and passed it the URL that we get in the main API call (loaded from the JSON file).

Now we should define this function in the methods object like this (I'm showing the contents of the whole script tag):

import pokemonData from './assets/pokemonapi.json';

export default {
  data() {
    return {
      pokemonList: pokemonData.results,
      searchTerm: '',
      selectedPokemon: null
    }
  },
  computed: {
    filteredPokemonList() {
      return this.pokemonList.filter(pokemon => pokemon.name.includes(this.searchTerm));
    }
  },
  methods: {
    async showPokemon(url) {
      const response = await fetch(url);
      if (!response.ok) {
        console.error(`Error fetching Pokemon: ${response.statusText}`);
        return;
      }

      this.selectedPokemon = await response.json();
      console.log(this.selectedPokemon);
    }
  }
}

To show the selected Pokemon, we'll add a bit of HTML:

<div class="pokemon-details" v-if="selectedPokemon">
  <h2>{{ selectedPokemon.name }}</h2>
  <img :src="selectedPokemon.sprites.front_default" alt="selectedPokemon.name">
  <p>Height: {{ selectedPokemon.height }}</p>
  <p>Weight: {{ selectedPokemon.weight }}</p>

  <div v-for="(stat, index) in selectedPokemon.stats" :key="index">
    <p>{{ stat.stat.name }}: {{ stat.base_stat }}</p>
  </div>
</div>

We're using v-if="selectedPokemon" so that the line {{ selectedPokemon.name }} doesn't throw an error for trying to access a property that doesn't exist on the object selectedPokemon (which is initialized as null in the beginnning).

We're using v-for to loop through all the elements of the stats array and output the name and base_stat properties.

To make it look nicer, we'll use a bit of CSS:

.pokemon-details {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 30%;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #000;
  border-radius: 10px;
  color: #000;
  text-transform: capitalize;
}

.pokemon-details img {
  width: 100px;
  height: 100px;
}

For reference, for those following the tutorial to the dot, here's the full listing of HelloWorld.vue file:

<script>
import pokemonData from './assets/pokemonapi.json';

export default {
  data() {
    return {
      pokemonList: pokemonData.results,
      searchTerm: '',
      selectedPokemon: null
    }
  },
  computed: {
    filteredPokemonList() {
      return this.pokemonList.filter(pokemon => pokemon.name.includes(this.searchTerm));
    }
  },
  methods: {
    async showPokemon(url) {
      const response = await fetch(url);
      if (!response.ok) {
        console.error(`Error fetching Pokemon: ${response.statusText}`);
        return;
      }

      this.selectedPokemon = await response.json();
      console.log(this.selectedPokemon);
    }
  }
}
</script>

<template>
  <header>
    <img alt="Vue logo" class="logo" src="./assets/logo.webp" />
  </header>

  <main>
    <div class="search-container">
      <input class="search-box" type="text" placeholder="Search..." v-model="searchTerm">
    </div>

    <div class="pokemon-details" v-if="selectedPokemon">
      <h2>{{ selectedPokemon.name }}</h2>
      <img :src="selectedPokemon.sprites.front_default" alt="selectedPokemon.name">
      <p>Height: {{ selectedPokemon.height }}</p>
      <p>Weight: {{ selectedPokemon.weight }}</p>

      <div v-for="(stat, index) in selectedPokemon.stats" :key="index">
        <p>{{ stat.stat.name }}: {{ stat.base_stat }}</p>
      </div>
    </div>

    <ul>
      <li v-for="pokemon in filteredPokemonList" :key="pokemon.id" class="pokemon-item">
        <a href="#" @click="showPokemon(pokemon.url)">{{ pokemon.name }}</a>
      </li>
    </ul>
  </main>
</template>

<style scoped>
header {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.logo {
  margin: 0 2rem 0 0;
}

.search-container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  /* Change the direction to row */
  gap: 10px;
}

.search-box {
  width: 30%;
  height: 50px;
  font-size: 1.5em;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin: 40px 0;
  text-align: center;
}

.pokemon-item {
  float: left;
  margin: 10px;
}
.pokemon-item a {
  color: #000;
  text-decoration: none;
  font-size: 16px;
  transition: color 0.3s ease;
  text-transform: capitalize;
}

.pokemon-item a:hover {
  color: #3B4CCA;
}

ul {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 5px;
  list-style: none;
}

.pokemon-details {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 30%;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #000;
  border-radius: 10px;
  color: #000;
  text-transform: capitalize;
}

.pokemon-details img {
  width: 100px;
  height: 100px;
}
</style>

B e a utiful

At this point, we can search for some Pokemon (my son's favorite is, ofc, Pikachu), and if we click on it, we'll get something like this:

Deployment

If you'd like to host this on your web server, then first run npm run build and you'll get an output similar to this:

Now all you have to do is take the contents of the dist folder and 'paste' it on your static web server.

If you don't have a server of your own, then Vite has an extensive description for deploying your static pages (if you don't have the ) to many popular services like Github Pages, Netlify, Vercel, Surge, etc.

You can deploy to Github Pages in under 2 minutes by following their documentation.

Just for brevity sake the steps are as follows:

  • create a new public Github repository and name it username.github.io, where username is your username on GitHub.
  • clone the repo with git clone https://github.com/username/username.github.io
  • inside the folder copy the contents of the dist folder
  • commit and push the changes:
git add --all 
git commit -m "Initial commit"
git push -u origin main

Now your site will be visible online at https://username.github.io (again, where username is your Github username)

You can check my deployment here.

Conclusion

In this tutorial, you learned how to get started with using Vue.js 3 by building an application for searching Pokemon by using PokeAPI and making it publically accessible via Github Pages.

Please leave any comments and feedback in the discussion section below, and thank you for reading!

Written by Nikola Brežnjak