0% found this document useful (2 votes)
2K views2 pages

Nuxt 3 Cheatsheet

Nuxt 3 provides tools for building pages, routing, data fetching, state management, server-side functionality, and modals. Pages are defined in the 'pages' directory and routes are generated dynamically. Data can be fetched using composables like useFetch and useAsyncData. Shared state is managed with useState. Server routes and API endpoints are defined in the 'server' directory. Modals can be built with the <Teleport> component. Configuration is accessed via useRuntimeConfig().

Uploaded by

Sami Asmar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (2 votes)
2K views2 pages

Nuxt 3 Cheatsheet

Nuxt 3 provides tools for building pages, routing, data fetching, state management, server-side functionality, and modals. Pages are defined in the 'pages' directory and routes are generated dynamically. Data can be fetched using composables like useFetch and useAsyncData. Shared state is managed with useState. Server routes and API endpoints are defined in the 'server' directory. Modals can be built with the <Teleport> component. Configuration is accessed via useRuntimeConfig().

Uploaded by

Sami Asmar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

NUXT 3 ESSENTIALS

CHEAT SHEET

STARTING A NEW PROJECT PAGES


Create a project using nuxi: Nuxt generates each app route from the folder pages directory.

pages
$ npx nuxi init <project-name>
index.vue loads the root path /
$ cd <project-name> posts
$ npm install Installs dependencies […slug].vue […x] catch all route /posts/my-slug
$ npm run dev Runs the project index.vue /posts
users-[group] we can also add params inside a folder . /users-customer
[id].vue [ ] de ines a dynamic route with a param. /users-admin/123

FOLDER STRUCTURE Access directly inside the template

ASSETS - Uncompiled assets (like Sass, fonts Images) pages/users-[group]/[id].vue

COMPONENTS - Components are automatically imported <template>


based on the folder and ile name <p>{{ $route.params.group }} - {{ $route.params.id }}</p>
</template>
COMPOSABLES - Directory to automatically import your
composables into your application
Access inside script tag using Composition API
CONTENT - Contains iles to create a ile based CMS
pages/users-[group]/[id].vue
LAYOUTS - Application layouts
<script setup>
MIDDLEWARE - Custom functions to run before each
const route = useRoute()
page
const { group, id } = route.params
PAGES - Application views & routes from which the router
is dynamically generated </script>

PLUGINS - JS plugins run before Vue.js init

SERVER - Create serverless functions


DATA FETCHING
Nuxt provides useFetch, useLazyFetch, useAsyncData and
STATE MANAGEMENT useLazyAsyncData to handle data fetching within your application.
Nuxt provides useState composable to create a reactive and
SSR-friendly shared state across components. ⚠ useFetch, useLazyFetch, useAsyncData and useLazyAsyncData only
work during setup or Lifecycle Hooks

🚨 Never de ine const state = ref() outside of <script setup> or


setup() function. useFetch()

<script setup>
const { data: count, pending, refresh, error } = await useFetch('/api/count')
✅ Instead use const useX = () => useState('x') </script>

<template>
Page visits: {{ count }}
Basic </template>

<script setup>
const counter = useState('counter', () => Math.random() * 1000)
</script>
useAsyncData()

<script setup>
const { data } = await useAsyncData('count', () => $fetch('/api/count'))
Shared state </script>

Composables de ined inside ~/composables folder are auto- <template>


imported and with that we can share states and import them Page visits: {{ data }}
</template>
across the app.

composables/states.ts

export const useCounter = () => useState<number>('counter', () => 0) 👉 Di erence between useFetch and useAsyncData:
export const useColor = () => useState<string>('color', () => 'pink') useFetch receives a URL and gets that data, whereas useAsyncData might
have more complex logic.
app.vue
useFetch(url) is nearly equivalent to useAsyncData(url, () => $fetch(url))

<script setup>
const color = useColor() // Same as useState('color')
</script>
useLazyFetch() and useLazyAsyncData()
These composables behave identically to useFetch and useAsyncData with
<template>
<p>Current color: {{ color }}</p> the lazy: true option set. In other words, the async function does not block
</template> navigation.

f
f
ff
f

f
f
f
NUXT 3 ESSENTIALS
CHEAT SHEET

SERVER ROUTES TELEPORT


Files inside the ~/server/api are automatically pre ixed with /api in their route. For adding
<template>
server routes without /api pre ix, you can instead put them into ~/server/routes directory. <button @click="open = true">
Open Modal
</button>
server/api/route.post.js <Teleport to="body">
<div v-if="open" class="modal">
import { sendError } from "h3" <p>Hello from the modal!</p>
<button @click="open = false">
Close
</button>
export default defineEventHandler(async (event) => { </div>
const config = useRuntimeConfig() // Get the runtime config </Teleport>
</template>
const query = useQuery(event) // Get the query from the event
const body = await useBody(event) // Get the body from the event
const headers = useHead(event) // Get the headers from the event RUNTIME CONFIG
const cookies = useCookies(event) // Get the cookies from the event

Expose runtime con ig


// Throw error
if(something) {
nuxt.con ig.ts
return sendError(event, createError({
statusCode: 400, export default defineNuxtConfig({
runtimeConfig: {
statusMessage: ‘Error message’
apiSecret: process.env.API_SECRET,
})) public: {
} apiBase: process.env.API_BASE,
}
},
return {
})
// returns a response object
}
})
Accessing runtime con ig

Client
Matching route params <script setup>
const config = useRuntimeConfig()
Server routes can use dynamic parameters within brackets in the ile name like console.log('Runtime config:', config)
/api/hello/[name].ts and accessed via event.context.params. if (process.server) {
Catching all routes its as easy as using the spread operator […name] console.log('API secret:',
config.apiSecret)
}
/server/api/hello/[name].ts </script>

export default defineEventHandler(event => `Hello, ${event.context.params.name}!`)


Server

export default defineEventHandler(async


(event) => {
Matching HTTP Method const config = useRuntimeConfig()

Handle ile names can be su ixed with .get, .post, .put, .delete, ... to match request’s. return {
// returns a response object
}
/server/api/test.get.ts })

export default defineEventHandler(() => 'Test get handler')

/server/api/test.post.ts

export default defineEventHandler(() => 'Test post handler')

SERVER MIDDLEWARE
Nuxt will automatically read in any ile in the ~/server/middleware to create server
middleware for your project.

server/middleware/auth.js

export default defineEventHandler((event) => {


console.log('New request: ' + event.req.url) For more quality programming courses
})
insidewebdev
f
ff
f
f
f

f
f
f

You might also like