loading...
Cover image for NuxtJS cheat sheet 1

NuxtJS cheat sheet 1

adnanbabakan profile image Adnan Babakan (he/him) ・5 min read

Hey DEV.to community!

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

I mostly use Vue in a framework called NuxtJS. 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

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

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:

<template>
    <div>
        <h1>Hello Nuxt!</h1>
    </div>
</template>

Predefined structure

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

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 generate

Routing

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 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:

<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:

<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

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:

<template>
    <div>
        <nuxt-child />
    </div>
</template>

You can use your custom layouts like this:

<script>
    export default {
        layout: 'your-layout-name'
    }
</script>

Errors page

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:

<template>
    <div>
        Error code: {{ error.statusCode }}
    </div>
</template>

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

Navigation

Navigation in a NuxtJS app is super easy. There is a very handy component called <NuxtLink> which you use as below:

<template>
    <div>
        <nuxt-link to="/about">About</nuxt-link>
    </div>
</template>

Context

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:

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:

const {
    req,
    res,
    beforeNuxtRender
  } = context

And some only available in the client-side:

const {
    from,
    nuxtState,
  } = context

Redirecting

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

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

Showing error

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:

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

$nuxt

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

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:

<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

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!

<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:

Posted on by:

adnanbabakan profile

Adnan Babakan (he/him)

@adnanbabakan

I'm Adnan Babakan and I'm from Iran. I started programming since I was 8 and now I'm 19. I love programming!

Discussion

markdown guide
 

I tired to use nuxt auth and it was so horrible experience. I didn't have much experience setting up authorization and wanted to read the doc. But documentation was very short with no clear explanation.

 

Although I am not the creator of NuxtJS, I am sad that you found it horrible. Nuxt is really easy to use and the documentation is actually good. Auhtorization is something you should implement by yourself not a part of Nuxt, yet it provides you with things like middleware to make it easier.

 

Vue and nuxt are making things absurdly easy. I like them for that a lot.
I handled it on my own through jwt.