DEV Community

Cover image for NuxtJS cheat sheet 1
Adnan Babakan (he/him)
Adnan Babakan (he/him)

Posted on

NuxtJS cheat sheet 1

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
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Build your application for production:

nuxt build
Enter fullscreen mode Exit fullscreen mode

Launch a production server:

nuxt start
Enter fullscreen mode Exit fullscreen mode

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

nuxt generate
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

It is also possible to have a directory as a dynamic parameter holder:

|----pages
    |----_user/
        |----index.vue
        |----posts.vue
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

You can use your custom layouts like this:

<script>
    export default {
        layout: 'your-layout-name'
    }
</script>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

The context object has some properties only available in the server-side:

const {
    req,
    res,
    beforeNuxtRender
  } = context
Enter fullscreen mode Exit fullscreen mode

And some only available in the client-side:

const {
    from,
    nuxtState,
  } = context
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

$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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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:

Top comments (4)

Collapse
 
nomikz profile image
nomikz

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.

Collapse
 
adnanbabakan profile image
Adnan Babakan (he/him) • Edited

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.

Collapse
 
nomikz profile image
nomikz

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

Thread Thread
 
adnanbabakan profile image
Adnan Babakan (he/him)

Glad to hear that!