Getting started with Vue.js 2 by building a Giphy search application

TL;DR
This tutorial follows the same pattern as this Angular 2 post. You’ll learn how to use Vue CLI to build a Vue.js 2 application for searching Giphy’s gifs by using their API.
The main reason for making this post was to evaluate a bit more lightweight solution than Angular or React.
I’m using Vue.js 2, and I’ll be referring to it as just Vue.js in the rest of this post.
Introduction
Let’s be honest, even those of us that don’t actually hate the JavaScript ecosystem can understand the frustration with the fact that new JS frameworks are popping up all the time.
I stuck to the Angular bandwagon ever since version 1.0. Even though I would recommend starting a new SPA project with it, I must say that my recent research led me to believe that due to Vue’s progressive and flexible nature, it’s a perfect fit for the teams that have to rewrite old codebases one step at a time.
If you want to check out some detailed comparisons between popular frontend frameworks, here are two great posts:
- Angular vs. React vs. Vue: A 2017 comparison
- Vue.js vs. React, Angular, AngularJS, Ember, Knockout, Polymer, Riot
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 said, fasten your seatbelts, take a venti (or trenta) sized cup of coffee, and let’s go!
Demo app
As said, we’ll build an application for searching (and showing) gifs from the Giphy website by using their API.
You can fork the complete source code on Github.
Prerequisites
Make sure that you have the following tools installed:
- Node.js – step by step guide for both Windows and Mac
- Git – a fun getting started tutorial
Vue CLI
As their README says:
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 installing vue-cli
, run:
npm install -g @vue/cli
You can confirm that the installation went well if you run:
vue --help
⚠️ 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 (
vue --version
) as of this writing is2.9.3
.
Starting a new app with Vue CLI
We’ll call our app, originally, giphy-search
. So, let’s start a new app using vue-cli
:
vue init webpack giphy-search
You should get an output similar to this:
# nikola in ~/DEV/Vue [13:37:99]
? Project name giphy-search
? Project description Giphy search app with Vue.js
? Author Nikola Brežnjak <[email protected]> // I welcome spam ;)
? Vue build standalone
? Install vue-router? No
? Use ESLint to lint your code? Yes
? Pick an ESLint preset Standard
? Set up unit tests No
? Setup e2e tests with Nightwatch? No
? Should we run `npm install` for you after the project has been created? (recommended) npm
vue-cli · Generated "giphy-search".
# Installing project dependencies ...
npm notice created a lockfile as package-lock.json. You should commit this file.
added 1349 packages in 28.159s
Running eslint --fix to comply with chosen preset rules...
# ========================
> [email protected] lint /Users/nikola/DEV/TeltechRepos/FrontendEvaluation/Vue/giphy-search
> eslint --ext .js,.vue src "--fix"
# Project initialization finished!
# ========================
To get started:
cd giphy-search
npm run dev
Documentation can be found at https://vuejs-templates.github.io/webpack
After this command finishes, let’s cd
into the project and run it:
cd giphy-search
npm run dev
You should get:
DONE Compiled successfully in 3745ms
Your application is running here: http://localhost:8080
You should see the following page in your browser if you visit this link: 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:
As I said, this is an introduction tutorial to get you running fast so I won’t be going into any specific details this time (this is up for some other posts), so here we’ll only focus on the src
folder. The contents of that folder should be something like this:
Adding 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 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 HelloWorld.vue
file. This file contains the following (...
is used for brevity in the listing below):
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<h2>Essential Links</h2>
<ul>
...
</ul>
<h2>Ecosystem</h2>
<ul>
...
</ul>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
Without knowing anything about Vue.js, we can see where we 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.
Adding input and a button
Our basic application should have one input field and one button.
To do this, add the following code to the HelloWorld.vue
file:
<input name="search">
<button>Search</button>
Actions
Having a simple search input field and a button doesn’t help 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 we define a function that will handle button click in Vue:
<button @click="performSearch">Search</button>
But, now if open up your DevTools, you’ll see an error like:
webpack-internal:///./node_modules/vue/dist/vue.esm.js:592 [Vue warn]: Property or method "performSearch" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option or for class-based components, by initializing the property. See https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
found in
---> <HelloWorld> at src/components/HelloWorld.vue
<App> at src/App.vue
<Root>
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",
data() {
return {
msg: "Welcome to GiphySearch"
};
},
methods: {
performSearch: function() {
console.log("clicked");
}
}
};
</script>
With this, we defined the performSearch
function, which doesn’t accept any parameters and it does not return anything.
Taking input
What if we would like to print 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 to bind the input to the new searchTerm
variable.
Finally, change the performSearch
function to this:
performSearch: function() {
console.log(this.searchTerm);
}
Giphy search API
Finally, we come to the cool part, and that is to fetch some data from the service and to show it in our app (in our case, we’ll show images).
So, 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.
We need the search API. If you scroll a bit, you’ll find the following link:
http://api.giphy.com/v1/gifs/search?q=funny+cat&api_key=dc6zaTOxFJmzC
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 what the service returns. Something like:
In the next section, we’ll cover retrieving this data from within our app.
Vue.js HTTP requests
We have several options for doing 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 ~~ugly~~ not so nice JavaScript callbacks) and runs on both the client and the server (i.e. Node.js).
In your Terminal/Command prompt 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:
var link = "http://api.giphy.com/v1/gifs/search?api_key=dc6zaTOxFJmzC&q=";
var 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="title" v-model="searchTerm">
<button @click="performSearch()">Search</button>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "HelloWorld",
data() {
return {
msg: "Welcome to GiphySearch"
};
},
methods: {
performSearch: function() {
console.log(this.searchTerm);
var link = "http://api.giphy.com/v1/gifs/search?api_key=dc6zaTOxFJmzC&q=";
var apiLink = link + this.searchTerm;
axios
.get(apiLink)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
}
}
};
</script>
Now, if you run the app, enter something in the search box, and click the search button, you’ll see something like this in your console log:
You can see that we’re getting back the response
object and that in its data
property there are 25 objects, which hold information about the images that we want to show in our app.
And, well, this is all great now, but we don’t want to be logging out our objects to the console, we want to show them in our app.
To show the image, we need to position ourselves on the object images
, then original
, and finally on the url
property.
Also, we don’t want to just show one image but all of the images. We’ll use the v-for
directive for that:
<img v-for="g in giphies" :key="g.id" src="{{g.images.original.url}}">
For reference, here’s the full listing of HelloWorld.vue
file:
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<input name="title" v-model="searchTerm">
<button @click="performSearch()">Search</button>
<div>
<img v-for="g in giphies" :key="g.id" :src="g.images.original.url">
</div>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "HelloWorld",
data() {
return {
msg: "Welcome to GiphySearch",
searchTerm: "cat",
giphies: []
};
},
methods: {
performSearch: function() {
console.log(this.searchTerm);
var link = "http://api.giphy.com/v1/gifs/search?api_key=dc6zaTOxFJmzC&q=";
var apiLink = link + this.searchTerm;
axios
.get(apiLink)
.then(response => {
this.giphies = response.data.data;
})
.catch(error => {
console.log(error);
});
}
}
};
</script>
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, 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 recently in the JWT authentication in an Angular application with a Go backend post.
Conclusion
In this tutorial, you learned how to get started with using Vue.js by building an application for searching Giphy’s gifs by using their API.
Please leave any comments and feedback in the discussion section below!
Thank you for reading!
Getting started with #Vue.js 2 by building a #Giphy search application https://t.co/AV1kjK6C1m
— Nikola Brežnjak (@HitmanHR) March 26, 2018
Leave a Comment