NuxtJS cheat sheet 1
Tags: vue, nuxt, javascript
Published: 2020-09-16 23:19:17

Hey DEV.to community!

Previously I've published a series called Vue cheat sheet which is available here:

{% link https://dev.to/adnanbabakan/vue-cheat-sheet-1-194a %}

I mostly use Vue in a framework called [NuxtJS](https://nuxtjs.org/). NuxtJS is an awesome framework built on top of Vue. So here is a cheat sheet getting you started with NuxtJS.

Some codes are from the NuxtJS's official website.

# Table of content

* [Installation](#installation)
    * [Manually](#manual-installation)
    * [Predefined structure](#predefined-structure)
* [NuxtJS commands](#nuxtjs-commands)
* [Routing](#routing)
    * [Dynamic routes](#dynamic-routes)
* [Layouts](#layouts)
* [Errors page](#errors-page)
* [Navigation](#navigation)
* [Context](#context)
    * [Redirecting](#context-redirecting)
    * [Showing error](#context-error)
* [$nuxt](#dollar-nuxt)
    * [isOffline](#dollar-nuxt-is-offline)
    * [refresh](#dollar-nuxt-refresh)

# Installation <a name="installation"></a>

NuxtJS has two modes to get started. You can either create your own app and install NuxtJS as a dependency or use its predefined structure.

## Manually <a name="manual-installation"></a>

You can create a folder and start your project using the `npm init` command and install NuxtJS as a dependency:
```
npm i --save nuxt
```

And create a folder in your project root called `pages` and add a file called `index.vue` in it with the content below:
```vue
<template>
    <div>
        <h1>Hello Nuxt!</h1>
    </div>
</template>
```

## Predefined structure <a name="predefined-structure"></a>

If you want NuxtJS to provide you with a starting structure so you just start coding and having fun you can use the command below:
```
npx create nuxt-app <your-app-name>
```
_npx is installed along with npm, so don't worry!_

Run the command above and answer some questions (they are easy don't worry, you will pass!)

I prefer this method personally.

# NuxtJS commands <a name="nuxtjs-commands"></a>

Here is a list of common commands used in your Terminal/CMD/PowerShell to do something with NuxtJS!

Launch a dev server:
```
nuxt
```

Build your application for production:
```
nuxt build
```

Launch a production server:
```
nuxt start
```

Generate a static website, meaning that every route will be a static HTML file:
```nuxt
nuxt generate
```




# Routing <a name="routing"></a>

If you have ever set up a Vue project, you should know how much it takes to set up a proper routing. In NuxtJS, every Vue file inside the `pages` folder is a route instantly!

Having a structure as below:
```
|----pages/
    |----extra/
        |----index.vue
        |----about.vue
    |----index.vue
```

Will create a route available as below:
```
http://example.org/ => index.vue
http://example.org/extra => extra/index.vue
http://example.org/extra/about => extra/about.vue
```

## Dynamic routes <a name="dynamic-routes"></a>

A dynamic route can be defined using an underscore character prefixed in a directory or file name.

Having a structure as below:
```
|----pages/
    |----user/
        |----_id.vue
```

Gives you a dynamic route as `http://example.com/user/:id` which in it the `:id` can be anything. You can retrieve the value of this parameter in your component using the `asyncData` method:
```vue
<template>
    <div>
        <h1>Your id is {{ id }}</h1>
    </div>
</template>

<script>
	export default {
		async asyncData(context) {
			return {
				id: context.params.id
			}
		}
	}
</script>
```

You can use the destructuring syntax of JavaScript and make the code above even simpler:
```vue
<template>
    <div>
        <h1>Your id is {{ id }}</h1>
    </div>
</template>

<script>
	export default {
		async asyncData({ params }) {
			return {
				id: params.id
			}
		}
	}
</script>
```

It is also possible to have a directory as a dynamic parameter holder:
```
|----pages
    |----_user/
        |----index.vue
        |----posts.vue
```

This makes you enable to create dynamic routes such as `http://example.com/:user/` and `http://example.com/:user/posts` which is awesome!

# Layouts <a name="layouts"></a>

Layouts are the way you can define a template structure for your pages that is common between them. To add a layout just add it to your `layouts` directory. If you name it `default.vue` it will be used as default.

Always add the `<NuxtChild>` component to your layout so the content of the page using the layout gets rendered there.

Here is a simple layout:
```vue
<template>
    <div>
        <nuxt-child />
    </div>
</template>
```

You can use your custom layouts like this:
```vue
<script>
	export default {
		layout: 'your-layout-name'
	}
</script>
```

# Errors page <a name="errors-page"></a>

You can customize the errors page of your NuxtJS application. The errors page is surprisingly located at `layouts/error.vue` while you should treat it as a page and not a layout! Which means you shouldn't include the `<NuxtChild>` component in it!

You can get the error code inside your errors page using the `error` prop:
```vue
<template>
    <div>
        Error code: {{ error.statusCode }}
    </div>
</template>

<script>
	export default {
		props: ['error']
	}
</script>
```

# Navigation <a name="navigation"></a>

Navigation in a NuxtJS app is super easy. There is a very handy component called `<NuxtLink>` which you use as below:
```vue
<template>
    <div>
        <nuxt-link to="/about">About</nuxt-link>
    </div>
</template>
```

# Context <a name="context"></a>

The `context` is an everywhere-present object which holds really useful stuff and is like a saving angel! But to be more precise it is only available in `asyncData`, `plugins`, `middleware` and `nuxtServerInit`.

The `context` object is defined as below:
```javascript
const {
    app,
    store,
    route,
    params,
    query,
    env,
    isDev,
    isHMR,
    redirect,
    error,
    $config
  } = context
```

The `context` object has some properties only available in the server-side:
```javascript
const {
    req,
    res,
    beforeNuxtRender
  } = context
```

And some only available in the client-side:
```javascript
const {
    from,
    nuxtState,
  } = context
```

## Redirecting <a name="context-redirecting"></a>

Redirecting is one of the most common tasks done by the `context` object's `redirect` method:

```vue
<script>
	export default {
		middleware({ redirect }) {
			if (!someAuthentication) {
				redirect('/login')
			}
		}
	}
</script>
```

## Showing error <a name="context-error"></a>

If you ever caught and error and wouldn't know what to do with it, just let `context.error` show it! The `error` method of the `context` object lets you pass an error to it and it shows it in your errors page:

```vue
<script>
	export default {
		middleware({ error }) {
			try {
                something()
			} catch (err) {
				error(err)
			}
		}
	}
</script>
```

# $nuxt <a name="dollar-nuxt"></a>

The `$nuxt` object is available in your components via `this.$nuxt` and is available globally via `window.$nuxt` in case you wanted to use it outside of your components (which is discouraged and used as a last resort).

## isOffline <a name="dollar-nuxt-is-offline"></a>

There is a property called `isOffline` inside the `$nuxt` object which holds a boolean indicating the internet connection of the user. You can use it to show a disconnection message to user:
```vue
<template>
    <div>
        <div v-if="$nuxt.isOffline">You are offline!</div>
    </div>
</template>
```

Oh! And there is one called `isOnline` which acts the opposite!

## refresh <a name="dollar-nuxt-refresh"></a>

In case you want to refresh the page's data (provided by `asyncData` and `fetch`) you can simply use the `refresh` method of the `$nuxt` object and not hit the refresh button that hard!
```vue
<template>
    <div>
        <button @click="refreshThePage">Refresh</button>
    </div>
</template>

<script>
	export default {
		methods: {
			refreshThePage() {
				this.$nuxt.refresh()
            }
        }
	}
</script>
```

This will save you some traffic as well if you are using a server-side rendered NuxtJS application since this refresh won't hit the server again for rendering the page opposite of hard-refreshing the page.

---
I hope you enjoyed this cheat sheet! More is coming.

Check out my free Node.js Essentials E-book here:

{% link https://dev.to/adnanbabakan/nodejs-essentials-free-e-book-5319 %}