How to connect your GraphQL API to your VueJS Frontend

How to connect your GraphQL API to your VueJS Frontend

GraphQL gives you room to build your APIs with ease and saves ... It seems that front-end devs are tired of requesting for APIs every now and then.Now, we will build a very simple Vue app and we'll learn how connect it to our GraphQL API. If something is unclear during the creation of the ...

I recently wrote about how to create an API with Hasura’s GraphQL engine. If you are not familiar with GraphQL yet, I recommend reading this post first. Now, we will build a very simple Vue app and we’ll learn how connect it to our GraphQL API.

If something is unclear during the creation of the Vue app or if you want to see the full solution, you can always view the project on Github.

Table of Contents
  • Creating a Vue project
  • Movie list component]
  • Movie detail component
  • Add movie component
  • Connecting to GraphQL API
  • Fetch actual data from GraphQL API
  • Movies list
  • Add movie
  • What now?
  • Join the community
Creating a Vue project

Let’s create a Vue project in our terminal by running:

vue create harry-potter-app

Select the default preset and open the project in your favourite editor. In order to make the appearance of our app a little prettier, we add the Milligram library. In the public index.html, add these three lines inside the <head>:

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Roboto:300,300italic,700,700italic">

<link rel="stylesheet" href="//cdn.rawgit.com/necolas/normalize.css/master/normalize.css">

<link rel="stylesheet" href="//cdn.rawgit.com/milligram/milligram/master/dist/milligram.min.css">

Go to your terminal, cd into your project, and run your application by typing locally:

With yarn:

yarn serve

With npm:

npm run serve

You should see Vue’s Hello World page with the Vue logo:

When we look at our Harry Potter API that we created in the previous post, we can see that we have several tables: movies, characters, actors and scenes. What we want to in our Vue app is to create components for movie. In the end, we want a component for a list of movies that consists of several components that represent a single movie. And we want to create a component that allows us to add movies.

Movie list component

Let’s get started. First, we’ll register the MoviesList component to the App.vue file. Inside the file, we need to replace the <HelloWorld/> component with <movies-list/>. Now this will fail, because we haven’t registered our new component. A little further down in the same file in the components list, let’s import our renamed component from the right location and replace the HelloWorld component with the MoviesList component. When you’re done, it should look like this:

<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<movies-list/>
</div>
</template>

<script>
import MoviesList from "./components/MoviesList.vue";
export default {
name: "app",
components: {
MoviesList
}
};
</script>

Now, we need to rename the HelloWorld.vue file to MoviesList.vue. Inside the file, we’ll replace the <template>and the <script> so it looks like this:

<template>
<div>
<div v-for="movie in movies" :key="movie.id">{{movie.id}}</div>
</div>
</template>

<script>
export default {
name: "MoviesList",
data() {
return {
movies: [
{
id: "123123123",
title: "Harry Potter and the Order of the Phoenix",
director: "David Yates",
composer: "Nicholas Hopper",
release_date: "2007-07-11"
}
]
};
}
};
</script>

Let me explain what happens here. Inside the template, we add a <div> that iterates over all our movies with v-for. We have to tell Vue how to identify each movie, which we’ll do by their id. Using the double curly braces, we tell Vue what to display in the browser, which is in our case the id of the movies. Inside the <script> tag, we define what data should be displayed. For now, we display dummy data which is a movie with an ID that we defined. If you now look at the app in your browser, you’ll see the Vue logo and the id of the movie.


Movie detail component

As we said before, we also need a component to display one movie. The purpose of this being that we can later display a collection of actual MovieItems in the MoviesList, instead of using dummy data. So let’s go ahead and inside the components folder, let’s create a new file called MovieItem.vue. For each MovieItem in the MoviesList, we want to display the title, the director, the composer and the release date. So let’s go ahead and add the component to the MovieItem.vue file.

<template>
<div :key="movie.id">
<h3>{{ movie.title }}</h3>
<p>{{ movie.director }}</p>
<p>{{ movie.composer }}</p>
<span>{{ movie.release_date }}</span>
</div>
</template>

<script>
export default {
name: "MovieItem",
props: ["movie"]
};
</script>

Now, we’ll have to go back to MoviesList.vue, and change it, so that we can display the actual MovieItems in our list.

<template>
<div>
<movie-item v-for="movie in movies" :key="movie.id" :movie="movie"></movie-item>
</div>
</template>

<script>
import MovieItem from "./MovieItem";
export default {
name: "MoviesList",
components: { MovieItem },
data() {
return {
movies: [
{
id: "123123123",
title: "Harry Potter and the Order of the Phoenix",
director: "David Yates",
composer: "Nicholas Hopper",
release_date: "2007-07-11"
}
]
};
}
};
</script>

In order to do so, we need to change line 3 to use the <movie-item> component instead of a simple <div>. Also, in line 8, we need to import the MovieItem from its corresponding file. Finally, in line 11, we need to state that MovieItem is the component that is used inside the current file as an instance of a list of movies.

When you now refresh your browser, it should look like this:


Add movie component

Let’s now add the capability to add new movies to our application. In order to do so, inside the components folder, we’ll create a new file called AddMovie.vue and leave it empty for now. Now we’ll open App.vue and inside the <template>, we’ll add the <add-movie/> component before the <movies-list> component. Also, like with the MoviesList component, we need to import the component from the correct location and add the AddMoviescomponent to our components list. When you’re done, your <template> and <script> should look like this:

<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<add-movie/>
<movies-list/>
</div>
</template>

<script>
import MoviesList from "./components/MoviesList.vue";
import AddMovie from "./components/AddMovie.vue";
export default {
name: "app",
components: {
MoviesList,
AddMovie
}
};
</script>

Inside the AddMovie.vue file, we’ll add a form to create new movies. When we have a look at our API, we can see what fields the movie table has. For now, we want to be able to create a movie that has a title, a director, a composer and a release date. The file should look like this:

<template>
<form @submit="submit">
<fieldset>
<input type="text" placeholder="Title" v-model="title">
<input type="text" placeholder="Director" v-model="director">
<input type="text" placeholder="Composer" v-model="composer">
<input type="text" placeholder="Release date" v-model="release_date">
</fieldset>
<input class="button-primary" type="submit" value="Send">
</form>
</template>

<script>
export default {
name: "AddMovie",
data() {
return {
title: "",
director: "",
composer: "",
release_date: ""
};
}
};
</script>

It is a very simple form that allows us to enter the fields for a movie and submit. Note that we haven’t added any methods to the component yet, so nothing happens if we click the submit button.

When you refresh your browser, you should see this:

Connecting to GraphQL API

The next step is to connect our Vue app to our GraphQL API that we created in the last post, so that we can display actual data instead of dummy data. Let’s go ahead and get started.

In the previous post, we’ve seen how we can run queries in the GraphiQL tool. We can go to the Hasura console and in GraphiQL, let’s test the methods to get a list of all movies, as well as the functionality to add a new movie:

query getMovies {
movies {
id
title
director
composer
release_date
}
}

mutation addPost($title:String!, $director:String!, $composer:String!, $release_date:date!) {
insert_movies(objects:[{
title:$title,
director:$director,
composer:$composer,
release_date:$release_date
}]) {
returning {
id
}
}
}

Now, in from Vue project, we want to invoke exactly these methods. In order to do that, we will use the Apollo client. Apollo is a GraphQL platform that allows you to make queries to your API in a simplified language. Let’s install Apollo by running this command in the command line (in your project folder):

with npm:

npm install apollo-client apollo-cache-inmemory apollo-link-http graphql-tag graphql --save

with yarn:

yarn add vue-apollo graphql apollo-client apollo-link apollo-link-http apollo-cache-inmemory graphql-tag

First, we need to establish the link to our Hasura project and to instantiate Apollo. Change your main.js so it looks as follows.

import Vue from 'vue';
import App from './App.vue';
import { createProvider } from './vue-apollo';
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';

import VueApollo, { ApolloProvider } from 'vue-apollo';

Vue.config.productionTip = false;

const httpLink = new HttpLink({
uri: 'https://graphql-harry-potter-api.herokuapp.com/v1alpha1/graphql'
});

const apolloClient = new ApolloClient({
link: httpLink,
cache: new InMemoryCache(),
connectToDevTools: true
});

Vue.use(VueApollo);

const apolloProvider = new VueApollo({
defaultClient: apolloClient
});

new Vue({
el: '#app',
apolloProvider,
render: h => h(App)
});

Let’s go through this. First, we need to import the libraries we just installed, because we will use them in this file. Using HttpLink, we establish a connection to our GraphQL API on lines 12–14. You find your own custom link in the GraphiQL tool on your Hasura project:

Next, in lines 16–20, we create an instance of the ApolloClient. As arguments, we pass our HttpLink, so that the data gets polled from the correct API. Next, we pass our cache. InMemoryCache is the default cache implementation for ApolloClient, so we use this one. Finally, we pass the option to connect to dev tools, so that we get an Apollo tab in our chrome inspector in case we have to debug.

On line 22, we configure our Vue instance to use VueApollo.

In order to to be able to make queries and mutations from our Vue app, we need to create an instance of ApolloProvider (lines 24–26). We’ll pass it our Apollo client with which we will commit these operations.

Finally, on lines 28–32, we launch our Vue app where our Apollo provider is passed, so that we can make database queries and manipulations throughout our app.

Fetch actual data from GraphQL API

So far, we’ve been displaying dummy data in our Vue frontend. Now, we want to display actual data. In our MoviesList, we want to display the movies that are currently stored in our database. Also, we want to be able to add movies, so that they get saved in our database and displayed in our frontend.

Movies list

In order to display movies from our database, let’s change MoviesList.vue to the following:

<template>
<div>
<movie-item v-for="movie in movies" :key="movie.id" :movie="movie"></movie-item>
</div>
</template>

<script>
import MovieItem from "./MovieItem";
import gql from "graphql-tag";
const GET_MOVIES = gql query getMovies { movies { id title director composer release_date } };
export default {
name: "MoviesList",
components: { MovieItem },
data() {
return {
movies: []
};
},
apollo: {
movies: {
query: GET_MOVIES
}
}
};
</script>

Inside the <script> tag, we need to import GraphQL, which will allow us to make queries. On lines 11–21, we define the GraphQL query to retrieve the list of movies.

Inside the export default function, we remove the dummy data and return the list of movies that we poll from the database. We also need to tell Apollo which query should be sent to the API, and we pass the GET_MOVIES query that we defined earlier.

When we refresh the browser, we can see the whole list of movies from our database:

Yay!

Add movie

So far, when we submit our form, nothing happens. We now want to be able to add movies over our form. For this, we need some changes in our AddMovie.vue file:

<template>
<form @submit="submit">
<fieldset>
<input type="text" placeholder="Title" v-model="title">
<input type="text" placeholder="Director" v-model="director">
<input type="text" placeholder="Composer" v-model="composer">
<input type="text" placeholder="Release date" v-model="release_date">
</fieldset>
<input class="button-primary" type="submit" value="Send">
</form>
</template>

<script>
import gql from "graphql-tag";
import { InMemoryCache } from "apollo-cache-inmemory";
const ADD_MOVIE = gql mutation addMovie( $title: String! $director: String! $composer: String! $release_date: date! ) { insert_movies( objects: [ { title: $title director: $director composer: $composer release_date: $release_date } ] ) { returning { id } } };
export default {
name: "AddMovie",
data() {
return {
title: "",
director: "",
composer: "",
release_date: ""
};
},
apollo: {},
methods: {
submit(e) {
e.preventDefault();
const { title, director, composer, release_date } = this.$data;
this.$apollo.mutate({
mutation: ADD_MOVIE,
variables: {
title,
director,
composer,
release_date
},
refetchQueries: ["getMovies"]
});
}
}
};
</script>

Again, inside the <script> tag, we need to import GraphQL. Also, we need to import the InMemoryCache. We’ll see why in just a bit.

In lines 17–39, we define our mutation to add movies to our database. First, we define the parameters that are passed. Second, we pass them as an object for a movie to be inserted. And third, we state the return value of our mutation which is, in our case the id of the movie that we just created.

The most substantial change inside the export default function is reflected in lines 52–67 where define what happens when the submit button is clicked. First, we need to prevent the default behaviour of a form being submitted when clicking on the button. Then, we define the data that is passed to the mutation. Next, we call our mutation on the $apollo instance and we pass the variables for the object creation. In the end, we need to refresh the movies list, because we don’t want to reload the browser for the newly added movie to appear in the list. For this, we need our cache. Because we ran the query to list movies before, we can just refetch it from the cache.

What now?

Good job! We now created a small Vue app and connected it to our GraphQL API. This was quite easy, wasn’t it? But this is just the beginning! There are a lot more features that can be added to our app. For example updating and deleting movies. Or displaying the characters and their corresponding actors for each movie. Check out the Hasura documentation. You can find everything that you need to extend this app.


Originally published by Marion Schleifer  at medium.com

==========================================================


Learn More

☞ Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

☞ Nuxt.js - Vue.js on Steroids

☞ Build Web Apps with Vue JS 2 & Firebase

☞ The Modern GraphQL Bootcamp (Advanced Node.js)

☞ NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

☞ GraphQL with React: The Complete Developers Guide

☞ Build a CMS with Laravel and Vue

☞ Vuejs 2 Authentication Tutorial

☞ GraphQL Tutorial: Understanding Spring Data JPA/SpringBoot

☞ GraphQL API with AWS and Use with React

☞ Build a Simple Web App with Express, Angular, and GraphQL

10 Best Vue Icon Component For Your Vue.js App

10 Best Vue Icon Component For Your Vue.js App

In this article, I will collect 10 Vue icon component to bring more interactivity, better UI design to your Vue application.

Icons are the vital element of the user interface of the product enabling successful and effective interaction with it. In this article, I will collect 10 Vue icon component to bring more interactivity, better UI design to your Vue application.

1. Animated SweetAlert Icons for Vue

A clean and simple Vue wrapper for SweetAlert's fantastic status icons. This wrapper is intended for users who are interested in just the icons. For the standard SweetAlert modal with all of its bells and whistles, you should probably use Vue-SweetAlert 2

Demo: https://vue-sweetalert-icons.netlify.com/

Download: https://github.com/JorgenVatle/vue-sweetalert-icons/archive/master.zip

2. vue-svg-transition

Create 2-state, SVG-powered animated icons.

Demo: https://codesandbox.io/s/6v20q76xwr

Download: https://github.com/kai-oswald/vue-svg-transition/archive/master.zip

3. Vue-Awesome

Awesome SVG icon component for Vue.js, with built-in Font Awesome icons.

Demo: https://justineo.github.io/vue-awesome/demo/

Download: https://github.com/Justineo/vue-awesome/archive/master.zip

4. vue-transitioning-result-icon

Transitioning Result Icon for Vue.js

A scalable result icon (SVG) that transitions the state change, that is the SVG shape change is transitioned as well as the color. Demonstration can be found here.

A transitioning (color and SVG) result icon (error or success) for Vue.

Demo: https://transitioning-result-icon.dexmo-hq.com/

Download: https://github.com/dexmo007/vue-transitioning-result-icon/archive/master.zip

5. vue-zondicons

Easily add Zondicon icons to your vue web project.

Demo: http://www.zondicons.com/icons.html

Download: https://github.com/TerryMooreII/vue-zondicons/archive/master.zip

6. vicon

Vicon is an simple iconfont componenet for vue.

iconfont
iconfont is a Vector Icon Management & Communication Platform made by Alimama MUX.

Download: https://github.com/Lt0/vicon/archive/master.zip

7. vue-svgicon

A tool to create svg icon components. (vue 2.x)

Demo: https://mmf-fe.github.io/vue-svgicon/v3/

Download: https://github.com/MMF-FE/vue-svgicon/archive/master.zip

8. vue-material-design-icons

This library is a collection of Vue single-file components to render Material Design Icons, sourced from the MaterialDesign project. It also includes some CSS that helps make the scaling of the icons a little easier.

Demo: https://gitlab.com/robcresswell/vue-material-design-icons

Download: https://gitlab.com/robcresswell/vue-material-design-icons/tree/master

9. vue-ionicons

Vue Icon Set Components from Ionic Team

Design Icons, sourced from the Ionicons project.

Demo: https://mazipan.github.io/vue-ionicons/

Download: https://github.com/mazipan/vue-ionicons/archive/master.zip

10. vue-ico

Dead easy, Google Material Icons for Vue.

This package's aim is to get icons into your Vue.js project as quick as possible, at the cost of all the bells and whistles.

Demo: https://material.io/resources/icons/?style=baseline

Download: https://github.com/paulcollett/vue-ico/archive/master.zip

I hope you like them!

Collection of 10 Vue Markdown Component for Vue.js App in 2020

Collection of 10 Vue Markdown Component for Vue.js App in 2020

Markdown is a way to style text on the web. The 10 Vue markdown components below will give you a clear view.

Markdown is a way to style text on the web. You control the display of the document; formatting words as bold or italic, adding images, and creating lists are just a few of the things we can do with Markdown.

The 10 Vue markdown components below will give you a clear view.

1. Vue Showdown

Use showdown as a Vue component.

View Demo

Download Source

2. showdown-markdown-editor

A markdown editor using codemirror and previewer using showdown for Vue.js.

View Demo

Download Source

3. markdown-it-vue

The vue lib for markdown-it.

View Demo

Download Source

4. perfect-markdown

perfect-markdown is a markdown editor based on Vue & markdown-it. The core is inspired by the implementation of mavonEditor, so perfect-markdown has almost all of the functions of mavonEditor. What's more, perfect-markdown also extends some features based on mavonEditor.

View Demo

Download Source

5. v-markdown-editor

Vue.js Markdown Editor component.

View Demo

Download Source

6. markdown-to-vue-loader

Markdown to Vue component loader for Webpack.

View Demo

Download Source

7. fo-markdown-note Component for Vue.js

fo-markdown-note is a Vue.js component that provides a simple Markdown editor that can be included in your Vue.js project.

fo-markdown-note is a thin Vue.js wrapper around the SimpleMDE Markdown editor JavaScript control.

View Demo

Download Source

8. Vue-SimpleMDE

Markdown Editor component for Vue.js. Support both vue1.0 & vue2.0

View Demo

Download Source

9. mavonEditor

A nice vue.js markdown editor. Support WYSIWYG editing mode, reading mode and so on.

View Demo

Download Source

10. vue-markdown

A Powerful and Highspeed Markdown Parser for Vue.

View Demo

Download Source

Thank for read!

Collection of 15 Vue Input Component for Your Vue.js App

Collection of 15 Vue Input Component for Your Vue.js App

Vue input component gives you a baseline to create your own custom inputs. It consists of a prepend/append slot, messages, and a default slot. In this article I will share 15 Vue input components to you.

Vue input component gives you a baseline to create your own custom inputs. It consists of a prepend/append slot, messages, and a default slot. In this article I will share 15 Vue input components to you.

1. Maska
  • No dependencies
  • Small size (~2 Kb gziped)
  • Ability to define custom tokens
  • Supports repeat symbols and dynamic masks
  • Works on any input (custom or native)

Demo

Download


2. v-range-flyout

A vue component that wraps a input type=number with a customizable range slider flyout with 2-way binding.

Demo

Download


3. vue-tel-input

International Telephone Input with Vue.

Demo

Download


4. Restricted Input

Allow restricted character sets in input elements.

Features

  • Disallow arbitrary characters based on patterns
  • Maintains caret position
  • Format/Update on paste
  • Works in IE11+

Demo

Download


5. Vue Currency Input

The Vue Currency Input plugin allows an easy input of currency formatted numbers.

Demo

Download


6. vue-fields

Input components for vue.js.

Demo

Download


7. vue-material-input

Simple example of issue I am seeing with input labels.

Demo

Download


8. vue-tribute

A Vue.js wrapper for Zurb's Tribute library for native @mentions.

Demo

Download


9. vue-number-smarty

Number input with rich functionality for Vue.js.

Features

  • integer/float
  • signed/unsigned
  • step size
  • increment/decrement value by scrolling when focused
  • align variants
  • min and max boundaries
  • max length of integer part (only for float type)
  • max length of float part (only for float type)
  • max length of string
  • error state
  • readonly state
  • theme options

Demo

Download


10. Vue input mask

Super tiny input mask library for vue.js based on PureMask.js (~2kb) exposed as directive. No dependencies.

Demo

Download


11. vue-r-mask

mask directive for vue.js

  • Template similar to javascript regular expression. /\d{2}/
  • Directive useful for your own input or textarea.
  • Arbitrary number of digits in template /\d{1,10}/

Demo

Download


12. Vue IP

An ip address input with port and material design support.

Demo

Download


13. v-money Mask for Vue.js

Tiny input/directive mask for currency

Features

  • Lightweight (<2KB gzipped)
  • Dependency free
  • Mobile support
  • Component or Directive flavors
  • Accept copy/paste
  • Editable

Demo

Download


14. Vue Masked Input

Dead simple masked input component for Vue.js 2.X. Based on inputmask-core.

Demo

Download


15. VueJS input component

Mobile & Desktop friendly VueJS input component
Features used
CSS variables
Vue's transition-group
Flexbox

Demo


I hope you like them!