Universal Vue.js application with Nuxt.js part#1 nuxt structure, installation and Configuration, Global CSS and CSS frameworks, Asynchronous data
Repository
https://github.com/nuxt/nuxt.js
What Will I Learn?
- Nuxt.js structure
- Installation and configuration Nuxt.js
- Create a global CSS and combination with CSS frameworks
- AJAX request in Nuxt.js
- Asynchronous data in Nuxt.js
Requirements
- Basic Javascript Es6
- Basic Vuejs
- Install Nuxt.js
Resources
Nuxt.js Website - https://nuxtjs.org/
Nuxt.js Github. - https://github.com/nuxt/nuxt.js
Vue-Cli - https://github.com/vuejs/vue-cli
Poke API - https://pokeapi.co/
Axios - https://github.com/axios/axios
Bootstrap NPM- https://www.npmjs.com/package/bootstrap
Difficulty
- Basic
Tutorial content
I will share the tutorial on Nuxt.js, we will start from the beginning about Nuxt.js, I hope you are familiar with Vue.js and already have basic in javascript es6 because Nuxt.js will be very related to Vue.js.
What is nuxt.js ?
Nuxt.js is a universal Vue.js application. that means we have server-side rendering (SSR) for our Vue app. if we usually use Vue.js as the frontend only, then by using Nuxt.js we also can use it at the backend.
Why use Nuxt.js ?
There are some problems when you want to make Single Page Application such as loading is too long because waiting for javascript file loaded or there is problems Search engine optimization (SEO) section because it can not read the contents of our application. So if we use Nuxt.js we will render the javascript files through the server so we can safely use Vue.js universally that is on Frontend and Backend.
Installation
We start installing Nuxt.js on our project, to install it you can go to official documentation from Nuxt.js https://nuxtjs.org/guide/installation or you can follow this tutorial based on my experience using Nuxt.js. Before installing the nuxt.js package via NPM. you must install Vue-cli first.
Install Vue-cli : npm install -g vue-cli
Install Package Nuxt.js: $ vue init nuxt-community/starter-template Millea-nuxt
Vue-cli will automatically generate files from nuxt.js and to install the packages we can go into the project-name we have created and do the NPM install.
When finished we can run it premises using npm run dev
and we can open in browser http://localhost: 3000/
Display and basic pages
Now we will learn how to structure the folders in Nuxt.js and see the initial view. in Nuxt.js there are 2 important folders that set the view that will be in the rendering of the layout and pages folder.
I will explain the usefulness of the folder.
1. Layout
In the layout folder, there is the default.vue file, this file is a useful view as a view that will be loaded in our application.
The structure
<template>
<div>
<nuxt/>
</div>
</template>
All loaded views will come from this file. <nuxt/>
tag represents the files to load. So the content in our app will be rendered in <nuxt/>
. So if in web application we have header and footer will be very suitable placed between tag <nuxt/>
.
Example:
<template>
<div>
<h1>This is my header</h1>
<nuxt/>
<h1>This is my footer</h1>
</div>
</template>
2. Pages
In this folder, we will create the display that will be displayed in the tag <nuxt/>
in default.vue file. The page we see in the browser is index.vue, I will create a file again to see the difference. I will create a file named newpage.vue. We must wrap the view in a root element.
Example:
<template>
<section class="container">
<h1>This the view from newPage.vue and I am on routing / newpage</h1>
</section>
</template>
When we create a new file in the page folder you will automatically assume as the new routing in your application.
Load own CSS and Combine with CSS frameworks
We will go to CSS, I will create a global CSS and we will learn how to combine it with other CSS frameworks. We can add the global CSS we have on the nuxt.config.js file.
- Load own CSS
Example:
module.exports = {
/*
** Headers of the page
*/
head: {
title: 'millenuxt',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'tutorial' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
/*
** Customize the progress bar color
*/
loading: { color: '#3B8070' },
css:[
'~/assets/css/main.css'
],
/*
** Build configuration
*/
build: {
/*
** Run ESLint on save
*/
extend (config, { isDev, isClient }) {
if (isDev && isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
}
}
}
- We can add CSS this way
css:[ '~/assets/css/main.css']
. You can customize your CSS file's directories. My file directory is in the folder assets/css/main.css and to see the result I will add a background to<body>
in main.css file.
main.css
body{
background: #73c000;
}
- Combine with CSS frameworks
we can also combine our CSS with CSS framework, all we need to do is we have to install our CSS framework via NPM. I will install the popular CSS framework that is bootstrap.
Install bootstrap via NPM : npm install bootstrap
After it has finished installing. I will give an example of its use in nuxt.config.js
Example:
module.exports = {
/*
** Headers of the page
*/
head: {
title: 'millenuxt',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'tutorial' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
/*
** Customize the progress bar color
*/
loading: { color: '#3B8070' },
css:[
'bootstrap/dist/css/bootstrap.css',
'~/assets/css/main.css'
],
/*
** Build configuration
*/
build: {
/*
** Run ESLint on save
*/
extend (config, { isDev, isClient }) {
if (isDev && isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
}
}
}
- We can add our bootstrap.css file directory 'bootstrap/dist/css/bootstrap.css' in
css: []
and I will add a navbar from bootstrap to see the result.
Navbar css from bootstrap
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Disabled</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
We will see the result as follows:
Install plugins and access API with Axios
In this section we will learn how to retrieve data from the API and present the data from the server side. We need an API for us to use as an example . There are many APIs that we can make an example. one of which I will use is https://pokeapi.co/ and I will use Axios plugin to do HTTP Request.
- Install plugin Axios
You can install it easily via NPM: npm install --save axios
- Axios configuration in nuxt.js
to use Axios there is a special trick so we do not always import on every page when want to use it. We can open our nuxt.config.js file and add some code.
module.exports = {
/*
** Headers of the page
*/
head: {
title: 'millenuxt',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'tutorial' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
/*
** Customize the progress bar color
*/
loading: { color: '#3B8070' },
css:[
'bootstrap/dist/css/bootstrap.css',
'~/assets/css/main.css'
],
build:{
vendor:['axios']
},
/*
** Build configuration
*/
build: {
/*
** Run ESLint on save
*/
extend (config, { isDev, isClient }) {
if (isDev && isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
}
}
}
we can add build: { vendor: ['axios']}
and we can create instance for axios.
- Create instance Axios
After configuring Axios in nuxt.config.js, We need to create Axios instance. I will create a new file inside the plugins folder.
axios.js
import axios from 'axios'
export default axios.create({
baseURL: 'http://pokeapi.co/api/v2/'
});
We must import Axios first import axios from 'axios'
and then create an Axios instance with the create()
method and we will create a baseURL
so we only declare it once.
- Use Axios in Nuxt.js
We will consume API with Axios in Nuxt.js and learn how to display the data in Nuxt.js. The first thing we will do is import axios.js file.
Code:
<script>
import axios from '~/plugins/axios'
export default{
asyncData(){
return axios.get('pokemon').then(res=>({
pokemons : res.data.results
}))
}
}
</script>
- We can import axios.js file like this
import axios from '~/plugins/axios'
. adjust to your file directory. AsyncData()
is the method provided by Nuxt.js. This method is useful so we can load data asynchronously. so the data will be loaded from the server side.- We have initialized the baseURL ('http://pokeapi.salestock.net/api/v2/') API in axios.js. So i added 'pokemon' on
axios.get ('pokemon')
. It's the same as http://pokeapi.salestock.net/api/v2/pokemon. We can use the callback function.then(res=>({}))
and the data received is on the callback paramater that is res. - Data contained in
res.data.results
then we save in variable pokemons.
- Display data in Nuxt.js
In the previous section, we have stored the data in pokemons, because the data in the form of object array we must use v-for to do the looping. I use CSS from bootstrap to create a list.
Code:
<div class="list-group">
<a href="#" class="list-group-item list-group-item-action active">
List data from API
</a>
<a v-for="item in pokemons" :key="item.name" href="#" class="list-group-item list-group-item-action">{{item.name}}</a>
</div>
To do v-for we need a unique key as an index in the iteration. We can use v-bind: key or shorthand :key and then we can loop v-for = "item in pokemons"
and display it with {{item.name}}
. The following is the contents of the data from http://pokeapi.salestock.net/api/v2/
The result
We can see the data we take from the fire http://pokeapi.salestock.net/api/v2/ we managed to display well and the data we display comes from the server instead of the client. thank you for following this tutorial, hopefully, help you!!
Curriculum
This is my first tutorial series on Nuxt.js in the next tutorial, I will share a more difficult tutorial about Nuxt.js
Thank you for your contribution.
While I liked the content of your contribution, I would still like to extend few advices for your upcoming contributions:
Looking forward to your upcoming tutorials.
Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.
To view those questions and the relevant answers related to your post, click here.
Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]
your suggestions I will do in the next tutorial, thank you @portugalcoin
Hey @duski.harahap
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!
Contributing on Utopian
Learn how to contribute on our website or by watching this tutorial on Youtube.
Want to chat? Join us on Discord https://discord.gg/h52nFrV.
Vote for Utopian Witness!