Youssef Samir

Get in touch

Nuxt.js

A cheat sheet for Nuxt.js features, configurations, and components for building powerful Vue.js applications.

Installation and Setup

Initialize a new project


npx nuxi init <project-name>

# OR

npm init nuxt-app <project-name>

Install dependencies


cd <project-name>

npm install

Start development server


npm run dev

Project Structure

  • Create a pages directory in the root of the project.
  • Create an index.vue in the pages directory serving as the home page by default.

mkdir pages

touch pages/index.vue

Example index.vue


<template>

<div>

<h1>Home Page</h1>

</div>

</template>

Routing and Navigation

Route Parameters

  • Use dynamic routes with an underscore _.

touch pages/user/_id.vue

Example _id.vue


<template>

<div>

<h1>User ID: {{ userId }}</h1>

</div>

</template>

<script setup>

import { useRoute } from 'vue-router'

const route = useRoute()

const userId = route.params.id

</script>
  • Use <NuxtLink> for navigation.

<template>

<div>

<NuxtLink to="/">Home</NuxtLink>

<NuxtLink to="/about">About</NuxtLink>

</div>

</template>

Layouts

  • Create a layouts directory for reusable layouts.

mkdir layouts

touch layouts/default.vue

Example default.vue


<template>

<div>

<header>Header</header>

<NuxtPage />

<footer>Footer</footer>

</div>

</template>

Page Metadata

definePageMeta

  • Use definePageMeta to define metadata for pages.

<script setup>

definePageMeta({

title: 'Home Page',

meta: [

{ name: 'description', content: 'This is the home page' }

]

})

</script>

Data Fetching

useFetch

  • Use useFetch for asynchronous data fetching.

<template>

<div>

<h1>Data: {{ data }}</h1>

</div>

</template>

<script setup>

const { data, pending, error } = await useFetch('/api/data-endpoint')

</script>

Error Handling

Create an error page

  • Create a layouts/error.vue file.

touch layouts/error.vue

Example error.vue


<template>

<div>

<h1>Error: {{ error.message }}</h1>

</div>

</template>

<script setup>

import { useError } from 'vue-error-boundary'

const error = useError()

</script>

createError

  • Use createError to handle errors.

<script setup>

import { createError } from 'nuxt/app'

const throwError = () => {

throw createError({

statusCode: 500,

statusMessage: 'Internal Server Error'

})

}

</script>

Server Routes

  • Create a server directory for server routes.

mkdir server

touch server/api/data-endpoint.js

Example data-endpoint.js


export default defineEventHandler((event) => {

return { message: 'Hello from server' }

})

#title