Originally published on my blog.
TL;DR
In this post, you'll learn how to use Vue CLI to build a Vue.js 3 application for searching Giphy's GIFs by using their API.
Introduction - The Battle is Over
Let's be honest; even those of us that actually don't hate the JavaScript ecosystem can understand the frustration with the fact that new JS frameworks are popping up all the time.
This was especially true some 2-3 years ago. 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 ever since version 1.0, but that started losing it's ooomph after version 2.
I believe that Vue.js (due to its progressive and flexible nature) is a perfect fit for the 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...
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 the 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! 💪
If you care about the hardcore metrics ⏱️ and want to check out some detailed comparisons between popular frontend frameworks, here are a few blog posts.
The Demo App
As said in the intro, we'll build an application for searching (and showing) Giphy GIFs by using their 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.js in the rest of this post.
Prerequisites
Make sure that you have the following tools installed:
- Node.js - here's a free but outdated step by step guide/book for both Windows and Mac. Or, really, just go to the main website and download the executable for your machine
- Git - here's a fun getting started tutorial in case you're new to it
Vue CLI
As their docs say:
Vue CLI aims to be the standard tooling baseline for the Vue ecosystem. It ensures the various build tools work smoothly together with sensible defaults so you can focus on writing your app instead of spending days wrangling with configurations. At the same time, it still offers the flexibility to tweak the config of each tool without the need for ejecting.
To install Vue CLI, run the following command (in your Terminal):
npm install -g @vue/cli
You can confirm that the installation went well if you run vue
and get an output with usage information.
⚠️ Just for reference (in case you follow this tutorial at a later stage and something is not the same as I output it here), my version (get the output by running
vue --version
in your Terminal) as of this writing is@vue/cli 4.5.12
.
Start a new app with Vue CLI
We'll call our app, originally 🙈, giphy-search
. So, to start a new app using Vue CLI, run:
vue create giphy-search
Make sure you select the option ❯ Default (Vue 3 Preview) ([Vue 3] babel, eslint)
and press ENTER
.
You should get an output similar to this:
Vue CLI v4.5.12
✨ Creating project in /Users/nikola/DEV/BLOG/giphy-search.
🗃 Initializing git repository...
⚙️ Installing CLI plugins. This might take a while...
🚀 Invoking generators...
📦 Installing additional dependencies...
📄 Generating README.md...
🎉 Successfully created project giphy-search.
After this command finishes, let's cd
into the project and run
it:
cd giphy-search
npm run serve
You should get this output:
DONE Compiled successfully in 3178ms
App running at:
- Local: http://localhost:8080/
- Network: http://192.168.8.189:8080/
Note that the development build is not optimized.
To create a production build, run npm run build.
You should see the following page in your browser if you open http://localhost:8080.
Folder structure
Now, let's open this project in the editor of your choice (I'm using Visual Studio Code), 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 Welcome to Your Vue.js App
, you'll see the string is within the App.vue
file. This file contains the following code:
<template>
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
components: {
HelloWorld
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
Without knowing much about Vue.js, you can see where you would change the Welcome to Your Vue.js App
text. So, let's change that to Welcome to GiphySearch
. While you do that, also remove the contents of the style
tag.
In the App.vue file, we have a template
tag that contains a standard HTML img
tag and an HelloWorld
tag, which is a so-called component. Here's the link to the documentation where you can learn more about components.
Add an input and a button
Our basic application should have one input field and one button.
To do this, adjust the template
in the HelloWorld.vue
file to contain only this:
<div class="hello">
<h1>{{ msg }}</h1>
<input name="search" />
<button>Search</button>
</div>
Actions
Having a simple search input field and a button doesn't do much. We want to click the button, and we want to output something to the console just to verify it's working correctly.
So, this is how you define a function that will handle a button click in Vue.js:
<button @click="performSearch">Search</button>
But, if you open your DevTools now and click the Search
button, you'll get an error like:
runtime-core.esm-bundler.js?5c40:38 [Vue warn]: Unhandled error during execution of native event handler
at <HelloWorld msg="Welcome to GiphySearch" >
at <App>
warn @ runtime-core.esm-bundler.js?5c40:38
logError @ runtime-core.esm-bundler.js?5c40:211
handleError @ runtime-core.esm-bundler.js?5c40:203
callWithErrorHandling @ runtime-core.esm-bundler.js?5c40:157
callWithAsyncErrorHandling @ runtime-core.esm-bundler.js?5c40:163
invoker @ runtime-dom.esm-bundler.js?830f:327
runtime-core.esm-bundler.js?5c40:217 Uncaught TypeError: _ctx.performSearch is not a function
at Object.onClick._cache.<computed>._cache.<computed> (HelloWorld.vue?fdab:6)
at callWithErrorHandling (runtime-core.esm-bundler.js?5c40:154)
at callWithAsyncErrorHandling (runtime-core.esm-bundler.js?5c40:163)
at HTMLButtonElement.invoker (runtime-dom.esm-bundler.js?830f:327)
That's because we haven't defined the performSearch
function anywhere.
Let's do that now. In the HelloWorld.vue
file, add the following function definition inside the script
tag, methods
object property:
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
},
methods: {
performSearch() {
console.log('clicked');
}
}
};
</script>
We defined the performSearch
function, which doesn't accept any parameters and it doesn't return anything. It just outputs clicked
in the console.
Gather input
What if we would like to output (to the console) the string that someone typed in the input field?
Well, first we need to add a new attribute to the input field:
<input name="title" v-model="searchTerm">
The v-model
is a directive that instructs Vue.js to bind the input to the new searchTerm
variable.
Finally, change the performSearch
function to this:
performSearch: function() {
console.log(this.searchTerm);
}
Technically, you could write this a bit differently, passing the
searchTerm
variable into theperformSearch
function as a parameter:performSearch: function(searchTerm) { console.log(searchTerm); } <button @click="performSearch(searchTerm)">Search</button>
I'd love to hear from you in the comments which approach is better in your opinion.
Giphy search API
Finally, we come to the cool part 🥶, and that is to fetch some data from the Giphy API and show it in our app.
How do we get this API? Well, if you do a simple Google search for giphy api
and open the first link, you'll get the documentation for their API.
You need to follow these instructions to create an account (and an app) to get an API key. You don't need an SDK solution at this point (you may want to go that route if you're going to make a mobile app that shows these images).
After you obtain your API key through their dashboard, you're going to be able to make search
(they offer a bunch more) API requests through their API explorer.
An API URL (obviously, with the fake API key) may look like this: https://api.giphy.com/v1/gifs/search?api_key=AbC&q=cats&limit=10&offset=0&rating=g&lang=en
Great, now we see what kind of a request we need to create to search Giphy's GIF database for a certain term.
If you open this link in the browser, you'll see that the service returns something like:
In the next section, we'll cover retrieving this data within our app.
⚠️ Since Giphy's rules now require you to add attribution, make sure you add it. I added the image in the footer with a link to their docs.
Vue.js HTTP requests
We have several options for making HTTP requests in Vue.js, and some may see this flexibility as a pro, and some may see it as a con. Either way, for more options, check out this post.
I chose to go with Axios, as it's a very popular JavaScript library for making HTTP requests. It's an HTTP client that makes use of the modern Promises API by default (instead of the not so nice JavaScript callbacks 🙂) and runs on both the client and the server (i.e., Node.js).
In your Terminal enter the following command to install Axios via npm:
npm install axios --save
Import Axios in the HelloWorld.vue
file just after the script
tag:
import axios from "axios";
The performSearch
function should now look like this:
let API_KEY = 'getYourOwn';
let link = `https://api.giphy.com/v1/gifs/search?api_key=${API_KEY}&limit=25&offset=0&rating=g&lang=en&q=`;
let apiLink = link + this.searchTerm;
axios
.get(apiLink)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
Just for reference, to put it all in one listing, the contents of the HelloWorld.vue
file should be:
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<input name="search" v-model="searchTerm" />
<button @click="performSearch()">Search</button>
</div>
<a href="https://developers.giphy.com/docs/api#quick-start-guide">
<img src="giphy.png" alt="" class="giphyAttribution" />
</a>
</template>
<script>
import axios from 'axios';
export default {
name: 'HelloWorld',
props: {
msg: String
},
methods: {
performSearch() {
let API_KEY = 'getYourOwn';
let link = 'https://api.giphy.com/v1/gifs/search?api_key=' + API_KEY + '&limit=25&offset=0&rating=g&lang=en&q=';
let apiLink = link + this.searchTerm;
axios
.get(apiLink)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
}
}
};
</script>
If you run the app and enter something in the input box, and then click the search button, you'll see something like this in your console log:
You can see that we're getting an object that in its data
property has another data
property (so meta 😎) that's an array with 25 objects, which holds the information about the images we'll show in our app.
Well, after a tongue twister in the previous sentence, this is all great, but we don't want to be logging our objects to the console; we want to show them in our app! 🙂
To show the GIF, you can choose any of the properties under the images
object, and use the url
property. I used fixed_height_small
in my example.
We don't want to just show one image but all of the images. We can use the v-for
directive for that:
<img v-for="g in giphies" :key="g.id" :src="g.images.fixed_height_small.url" />
For reference, here's the full listing of HelloWorld.vue
file:
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<input name="search" v-model="searchTerm" />
<button @click="performSearch()">Search</button>
<img v-for="g in giphies" :key="g.id" :src="g.images.fixed_height_small.url" />
</div>
<a href="https://developers.giphy.com/docs/api#quick-start-guide">
<img src="giphy.png" alt="" class="giphyAttribution" />
</a>
</template>
<script>
import axios from 'axios';
export default {
name: 'HelloWorld',
props: {
msg: String
},
data() {
return {
searchTerm: 'cats',
giphies: []
};
},
methods: {
performSearch() {
let API_KEY = 'getYourOwn';
let link = 'https://api.giphy.com/v1/gifs/search?api_key=' + API_KEY + '&limit=25&offset=0&rating=g&lang=en&q=';
let apiLink = link + this.searchTerm;
axios
.get(apiLink)
.then((response) => {
this.giphies = response.data.data;
})
.catch((error) => {
console.error(error);
});
}
}
};
</script>
B e a utiful
At this point, if we take a look at the app and search, for example, for 'cat coding' we'll get this:
Although the result doesn't look sleek (ha!, far from it 😳), our code does exactly what it's supposed to do. If you want it to look nicer, feel free to add more CSS.
Bulma is a cool framework that I used in the JWT authentication in an Angular application with a Go backend post in case you're interested in taking a look.
Conclusion
In this tutorial, you learned how to get started with using Vue.js 3 by building an application for searching Giphy's GIFs by using their API.
Please leave any comments and feedback in the discussion section below, and thank you for reading!
Top comments (0)